两种工厂方法区别
ThreadPoolExecutor是Executors类的底层实现,在JDK帮助文档中,有如此一段话:“强烈建议程序员使用较为方便的 Executors 工厂方法 Executors.newCachedThreadPool()(无界线程池,可以进行自动线程回收)、Executors.newFixedThreadPool(int)(固定大小线程池)和Executors.newSingleThreadExecutor()(单个后台线程),它们均为大多数使用场景预定义了设置。”
看了一下Executors.newFixedThreadPool(int)和Executors.newSingleThreadExecutor()的源码:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
发现newSingleThreadExecutor()与newFixedThreadPool(1)的区别就是newSingleThreadExecutor()是被FinalizableDelegatedExecutorService包装了一下,FinalizableDelegatedExecutorService的代码如下:
static class FinalizableDelegatedExecutorService
extends Delegated