# Java實戰系列 - 線程池中的線程出現異常

問題:線程池中的線程執行任務出現異常,該線程接下來的命運如何?

結論:線程會結束,線程池會新建線程替換該線程

驗證:編碼驗證,代碼如下

public class ThreadPoolExceptionTest {

    // 創建一個核心線程數、最大線程數都爲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
  • 總結:通過日誌線程的線程名稱可知,線程執行任務出現異常,該線程會結束,線程池會創建新的線程替換該線程執行其他任務。

本文完。

發佈了35 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章