关于 Executors.newSingleThreadExecutor()
本以为只是一个简单的单线程线程池,与 Executors.newFixedThreadExecutor(1)
类似,但它的 DOC
注释中又显式提到:
Unlike the otherwise equivalent {@code newFixedThreadPool(1)} the returned executor is guaranteed not to be reconfigurable to use additional threads.
与类似功能的 newFixedThreadPool(1)
不一样,该方法返回的线程池执行器不可以被重新配置以使用额外的线程。
关键在于不可以重新配置。来看看它的构造器:
1 2 3 4 5
| public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
static class FinalizableDelegatedExecutorService extends DelegatedExecutorService { FinalizableDelegatedExecutorService(ExecutorService executor) { super(executor); } protected void finalize() { super.shutdown(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
|
static class DelegatedExecutorService extends AbstractExecutorService { private final ExecutorService e; DelegatedExecutorService(ExecutorService executor) { e = executor; } public void execute(Runnable command) { e.execute(command); } public void shutdown() { e.shutdown(); } ... }
|
再看看 ThreadPoolExecutor
的实现:👇
1 2 3 4
|
public class ThreadPoolExecutor extends AbstractExecutorService
|
那我们试试,reconfigurable newSingleThreadExecutor
会怎样:👇
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @Test public void singleThreadPoolExecutorTest(){ ExecutorService fixed = Executors.newFixedThreadPool(1); ThreadPoolExecutor t1 = (ThreadPoolExecutor)fixed; t1.setCorePoolSize(2); ExecutorService single = Executors.newSingleThreadExecutor(); ThreadPoolExecutor t2 = (ThreadPoolExecutor)single; t2.setCorePoolSize(2); }
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
|