public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
总结:
- 核心线程数为0
- 最大线程数为Integer.MAX_VALUE,
- 使用SynchronousQueue,这里不会阻塞,因为execute用的是offer插入元素
- 理解synchronousQueue虽然使用了offer,但是如果前面的元素没有被消费那么后续的插入操作也是失败的,从这点上看synchronousQueue.offer是阻塞的
- 如果主线程提交任务的速度高于maximumPool中线程处理任务的速度时,CachedThreadPool会不断创建新线程。极端情况下,CachedThreadPool会因为创建过多线程而耗尽CPU和内存资源。因为SynchronousQueue不会阻塞,只会返回是否插入成功的标志,如果插入元素失败,则创建线程。