1.线程池
创建和销毁大量的线程,开销很大。
所以可以使用线程池,提取创建好多个线程,使用时直接获取,使用完毕后放回线程池中,避免了大量的创建和销毁操作。
优点:
- 提高响应速度
- 降低资源消耗
- 便于线程管理
具体实现:

Runnable接口的线程:
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class D26 {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(5);
service.execute(new TestThread());
service.execute(new TestThread());
service.execute(new TestThread());
service.shutdown();
}
}
class TestThread implements Runnable{
@Override
public void run() {
System.out.println("This is " + Thread.currentThread().getName() );
}
}
Callable接口的线程:
import java.util.concurrent.*;
public class D27 {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(5);
Future<Integer> r1 = service.submit(new Test2());
Future<Integer> r2 = service.submit(new Test2());
Future<Integer> r3 = service.submit(new Test2());
service.shutdown();
}
}
class Test2 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("This is " + Thread.currentThread().getName());
return 0;
}
}
博客介绍了Java中线程池的使用。创建和销毁大量线程开销大,使用线程池可预先创建多个线程,使用时获取、用完放回,避免大量创建和销毁操作。其优点包括提高响应速度、降低资源消耗、便于线程管理,还提及了Runnable和Callable接口线程的具体实现。
170万+

被折叠的 条评论
为什么被折叠?



