Executors的newSingleThreadExecutor()和newFixedThreadPool(1)有什么區(qū)別?
參考了一些文章,都說newSingleThreadExecutor()主要有兩個特性:
能保證執(zhí)行順序,先提交的先執(zhí)行。
當(dāng)線程執(zhí)行中出現(xiàn)異常,去創(chuàng)建一個新的線程替換之。
講到和newFixedThreadPool(1)的區(qū)別,都主要指出如下。
http://www.cnblogs.com/richaa...文章中:
和 newFixedThreadPool(1) 的區(qū)別在于,如果線程遇到錯誤中止,它是無法使用替代線程的。
http://blog.csdn.net/vking_wa...文章中:
如果當(dāng)前線程意外終止,會創(chuàng)建一個新線程繼續(xù)執(zhí)行任務(wù),這和我們直接創(chuàng)建線程不同,也和newFixedThreadPool(1)不同。
但經(jīng)過我的實驗(代碼如下),得出兩者都是一樣的,都保證了1和2。
// ExecutorService executorService = Executors.newSingleThreadExecutor();
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.execute(
() -> {
if (count == 100) {
thrownewIllegalStateException("handler exception");
}
System.out.println(Thread.currentThread()+" - testAsyncRunner1 run ... "+count);
}
);
運行結(jié)果:
Thread[pool-1-thread-1,5,main] - testAsyncRunner1 run ... 99
Exception in thread "pool-1-thread-1" java.lang.IllegalStateException: handler exception
at com.mxx.meal.common.core.async.AsyncHandlerFactoryTest.lambda$null$0(AsyncHandlerFactoryTest.java:32)
at com.mxx.meal.common.core.async.AsyncHandlerFactoryTest$$Lambda$2/830539025.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Thread[pool-1-thread-2,5,main] - testAsyncRunner1 run ... 101
創(chuàng)建newSingleThreadExecutor的源碼中,其實是在newFixedThreadPool(1)的基礎(chǔ)上包裝了FinalizableDelegatedExecutorService,請問下這個究竟有啥用?麻煩幫忙解答。
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
Executors的newSingleThreadExecutor()和newFixedThreadPool(1)有什么區(qū)別?
料青山看我應(yīng)如是
2019-03-01 10:31:38