不推荐使用Executors创建线程池
线程池不建议使用Executors 去创建,而是通过new ThreadPoolExecutor(…)的方式去创建,这样写会让你更加明确线程池的运行规则,规避资源耗尽的风险。
Executors的弊端如下:
(1)Executors.newFixedThreadPool和Executors.newSingleThreadExecutor:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
//队列的元素个数为Integer的最大值
public LinkedBlockingQueue() {
this(Integer.MAX_VALUE);
}
(2)Executors.newCachedThreadPool:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
以上两点是例子还有其它,在我们的开发中使用 new ThreadPoolExecutor(…) 的方式避免提交过多线程或线程队列堆积造成OOM的问题,当处理负荷时需要主动拒绝的方式有好的处理。