看看这两个方法的源码:
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>()));
}
可以看到,这两个方法返回的对象不一样,一个是ThreadPoolExecutor,而另外一个是FinalizableDelegatedExecutorService
FinalizableDelegatedExecutorService 只有finalize方法; 没有其他什么内容。其继承了DelegatedExecutorService。
static class FinalizableDelegatedExecutorService extends Executors.DelegatedExecutorService {
FinalizableDelegatedExecutorService(ExecutorService var1) {
super(var1);
}
protected void finalize() {
super.shutdown();
}
}
最关键部分还是在DelegatedExecutorService类中。
DelegatedExecutorService是AbstractExecutorService的子类,而与ThreadpoolExecutor是兄弟关系,
并没有提供修改线程大小的方法。这个类只提供了线程池中一些基本的方法。
但是
DelegatedExecutorService构造函数还是传入
ThreadpoolExecutor引用;、
这样虽然底层仍然使用的是threadPoolExecutor线程池,但是将部分核心的功能进行了隔离。只提供了抽象类需要的一些方法