"線程池中線程異常後:銷燬還是複用?"

一、一個線程池中的線程異常了,那麼線程池會怎麼處理這個線程?

需要說明,本文的線程池都是java.util.concurrent.ExecutorService線程池,本文將圍繞驗證閱讀源碼倆方面來解析這個問題。

二、代碼驗證

2.1 驗證execute提交線程池中

2.1.1 測試代碼:

   public class ThreadPoolExecutorDeadTest {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = buildThreadPoolExecutor();
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute-exception"));
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute"));


        Thread.sleep(5000);
        System.out.println("再次執行任務=======================");

        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute"));
    }


    public static ExecutorService buildThreadPoolExecutor() {
        return new ThreadPoolExecutor(5, 10, 30, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000), new ThreadFactoryBuilder().setNameFormat("test-%s").build()
                , new ThreadPoolExecutor.CallerRunsPolicy());
    }

    private static void exeTask(String name) {
        String printStr = "[thread-name:" + Thread.currentThread().getName() + ",執行方式:" + name + "]";
        if ("execute-exception".equals(name)) {
            throw new RuntimeException(printStr + ", 我拋異常了");
        } else {
            System.out.println(printStr);
        }
    }
}

2.1.2 執行結果如下:



 

 

2.1.3 結論:

execute 提交到線程池的方式,如果執行中拋出異常,並且沒有在執行邏輯中catch,那麼會拋出異常,並且移除拋出異常的線程,創建新的線程放入到線程池中。

2.2 驗證submit提交線程池中

2.2.1 測試代碼:

public class ThreadPoolExecutorDeadTest {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = buildThreadPoolExecutor();
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute-exception"));
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute"));


        Thread.sleep(5000);
        System.out.println("再次執行任務=======================");

        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute"));
    }


    public static ExecutorService buildThreadPoolExecutor() {
        return new ThreadPoolExecutor(5, 10, 30, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000), new ThreadFactoryBuilder().setNameFormat("test-%s").build()
                , new ThreadPoolExecutor.CallerRunsPolicy());
    }

    private static void exeTask(String name) {
        String printStr = "[thread-name:" + Thread.currentThread().getName() + ",執行方式:" + name + "]";
        if ("execute-exception".equals(name)) {
            throw new RuntimeException(printStr + ", 我拋異常了");
        } else {
            System.out.println(printStr);
        }
    }
}

2.2.2 執行結果如下:



 

 

2.2.3 結論:

submit 提交到線程池的方式,如果執行中拋出異常,並且沒有catch,不會拋出異常,不會創建新的線程。

三、源碼解析

3.1 java.util.concurrent.AbstractExecutorService#submit(java.lang.Runnable)



 

 

3.2 查看execute方法的執行邏輯java.util.concurrent.ThreadPoolExecutor#runWorker



 

 

3.3 java.util.concurrent.ThreadPoolExecutor#processWorkerExit



 

 

可以發現,如果拋出異常,會移除拋出異常的線程,創建新的線程。

3.4 爲什麼submit方法,沒有創建新的線程,而是繼續複用原線程?

還記得,我們在3.1的時候,發現submit也是調用了execute方法,但是在調用之前,包裝了一層 RunnableFuture,那一定是在RunnableFuture的實現 FutureTask中有特殊處理了,我們查看源碼可以發現。



 

 



 

 



 

 



 

 

但是,我們通過java.util.concurrent.FutureTask#get(),就可以獲取對應的異常信息。

四、總結

當一個線程池裏面的線程異常後:

當執行方式是execute時,可以看到堆棧異常的輸出,線程池會把這個線程移除掉,並創建一個新的線程放到線程池中
當執行方式是submit時,堆棧異常沒有輸出。但是調用Future.get()方法時,可以捕獲到異常,不會把這個線程移除掉,也不會創建新的線程放入到線程池中。

以上倆種執行方式,都不會影響線程池裏面其他線程的正常執行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章