线程池
- 线程池主要解决两个问题
- 1:控制线程的数量
- 线程过多会导致内存消耗大,CPU过度切换导致的并发
- 性能差等问题
- 2:重用线程
- 线程不应当随着任务的生命周期一致,避免频繁的创建和
- 销毁线程可以降低启动带来的不必要开销.
Demo
ExecutorService threadPool=Executors.newFixedThreadPool(2);
for (int i = 0; i < 5; i++) {
Runnable r=new Runnable() {
public void run() {
try {
Thread t= Thread.currentThread();
System.out.println(t.getName()+":正在执行任务");
Thread.sleep(5000);
System.out.println(t.getName()+"运行任务结束.");
} catch (Exception e) {
}
}
};
threadPool.execute(r);
System.out.println("指派了一个任务给线程池");
}
threadPool.shutdown();
System.out.println("线程池已关闭");