問題:線程池中的線程執(zhí)行任務出現(xiàn)異常,該線程接下來的命運如何疲恢?
結論:線程會結束凶朗,線程池會新建線程替換該線程
驗證:編碼驗證,代碼如下
public class ThreadPoolExceptionTest {
// 創(chuàng)建一個核心線程數(shù)显拳、最大線程數(shù)都為1的線程池棚愤,任務隊列最大容量為10
private static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10),
new java.util.concurrent.ThreadPoolExecutor.DiscardPolicy());
public static void main(String[] args) {
executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 0)));
try {
// 睡眠1秒,讓打印結果更明顯
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 1)));
executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 2)));
executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 3)));
executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 4)));
}
}
- 打印日志如下:
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
at com.lushwe.thread.ThreadPoolExceptionTest.lambda$main$0(ThreadPoolExceptionTest.java:25)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
pool-1-thread-2 1
pool-1-thread-2 0
pool-1-thread-2 0
pool-1-thread-2 0
- 總結:通過日志線程的線程名稱可知杂数,線程執(zhí)行任務出現(xiàn)異常宛畦,該線程會結束瘸洛,線程池會創(chuàng)建新的線程替換該線程執(zhí)行其他任務。
本文完刃永。