线程池底层实现
线程池的底层实现是:ThreadPoolExecutor
使用工厂类Executors快速创建预定义线程池
IDEA插件Alibaba Java Coding Guidelines,代码提示如下(马云不推荐使用啊)
线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
说明:Executors 返回的线程池对象的弊端如下:
1) FixedThreadPool 和 SingleThreadPool:
允许的请求队列长度为 Integer.MAX_VALUE(无限),可能会堆积大量的请求,从而导致 OOM。
2) CachedThreadPool:
允许的创建线程数量为 Integer.MAX_VALUE(无限),可能会创建大量的线程,从而导致 OOM。
预定义线程池
2. CachedThreadPool(典型的最大线程数是无限的线程池)
允许的创建线程数量为 Integer.MAX_VALUE(无限),可能会创建大量的线程,从而导致 OOM。
ExecutorService executorService = Executors.newCachedThreadPool();
//点击进入代码,查看实现:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
第一种写法(最简单):使用工厂类Executors快速创建线程池
ExecutorService executorService = Executors.newCachedThreadPool();
第二种写法(最原始):使用ExecutorService创建线程池
ExecutorService pool = new ThreadPoolExecutor(
0, //corePoolSize = 0
Integer.MAX_VALUE, //maximumPoolSize = 2147483647
60L, //keepAliveTime = 60
TimeUnit.MILLISECONDS,
new SynchronousQueue<Runnable>(),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
第三种写法(适中):使用ThreadPoolTaskExecutor简洁创建线程池
ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();
poolTaskExecutor.setQueueCapacity(0); //这个地方随便填
poolTaskExecutor.setCorePoolSize(0); //核心线程数是0,阻塞队列会选择new SynchronousQueue()
poolTaskExecutor.setMaxPoolSize(2147483647); // Integer.MAX_VALUE = 2147483647
poolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
poolTaskExecutor.setKeepAliveSeconds(60);
poolTaskExecutor.initialize();
扩展参考: 线程池之CachedThreadPool学习