创建 CachedThreadPool
自动创建但不用传参
ExecutorService ThreadPool = Executors.newCachedThreadPool();
分析一下它的源码,看里面是怎么创建 CachedThreadPool的
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- 第一个参数位置,corePoolSize为0,即每次线程池空闲的时候,都会把线程池中的所有线程销毁
- 第二个参数位置,maximumPoolSize,最大可创建线程的数量是Integer.MAX_VALUE,理论上可以达到的个数,但实际上嘛,没见过
- 第三个参数位置,KeepAliveTime,线程池空闲的时候,检测线程是不是空闲了 60秒,如果是就销毁线程
- 第四个参数位置,Unit,也就是 KeepAliveTime的时间单位,也就是秒
- 第五个参数位置,阻塞队列,SynchronousQueue,不存储任何任务,因为这个线程池理论可以创建Integer.MAX_VALUE个线程,也就是你过来,我就创建个线程去处理任务
测试 CachedThreadPool
public class TestCachedThreadPool {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newCachedThreadPool();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "运行了!!");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
for (int i = 0; i < 50; ++i) {
threadPool.submit(thread);
}
threadPool.shutdown();
}
}
好像还真是来一个任务,我创建一个线程去执行
从上面可以得知,CachedThreadPool是一个无上限创建线程的线程池,它的阻塞队列为 SynchronousQueue,它的核心线程数为0,它的 KeepAliveTime为60
与 FixedThreadPool有点相反,FixedThreadPool 创建的线程数是有限的,但它的 阻塞队列可以无上限存放任务
欢迎大家关注下个人的「公众号」:独醉贪欢