# Java實(shí)戰(zhàn)系列 - 線程池中的線程出現(xiàn)異常

問題:線程池中的線程執(zhí)行任務(wù)出現(xiàn)異常,該線程接下來的命運(yùn)如何?

結(jié)論:線程會結(jié)束,線程池會新建線程替換該線程

驗(yàn)證:編碼驗(yàn)證,代碼如下

public class ThreadPoolExceptionTest {

    // 創(chuàng)建一個(gè)核心線程數(shù)、最大線程數(shù)都為1的線程池,任務(wù)隊(duì)列最大容量為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秒,讓打印結(jié)果更明顯
            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
  • 總結(jié):通過日志線程的線程名稱可知,線程執(zhí)行任務(wù)出現(xiàn)異常,該線程會結(jié)束,線程池會創(chuàng)建新的線程替換該線程執(zhí)行其他任務(wù)。

本文完。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容