面試官:線程池如何按照core、max、queue的執行循序去執行?(內附詳細解析)

{"type":"doc","content":[{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"前言"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"這是一個真實的面試題。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"前幾天一個朋友在羣裏分享了他剛剛面試候選者時問的問題:"},{"type":"text","marks":[{"type":"strong"}],"text":"\"線程池如何按照core、max、queue的執行循序去執行?\""},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們都知道線程池中代碼執行順序是:"},{"type":"text","marks":[{"type":"strong"}],"text":"corePool->workQueue->maxPool"},{"type":"text","text":",源碼我都看過,你現在問題讓我改源碼?? "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"一時間羣裏炸開了鍋,小夥伴們紛紛打聽他所在的公司,然後拉黑避坑。"},{"type":"text","marks":[{"type":"strong"}],"text":"(手動狗頭,大家一起調侃٩(๑❛ᴗ❛๑)۶)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"關於線程池他一共問了這麼幾個問題:"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"線程池如何按照core、max、queue的順序去執行?"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"子線程拋出的異常,主線程能感知到麼?"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"線程池發生了異常改怎樣處理?"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"全是一些有意思的問題,我之前也寫過一篇很詳細的圖文教程:[【萬字圖文-原創】 | 學會Java中的線程池,這一篇也許就夠了!][1] ,不瞭解的小夥伴可以再回顧下~"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"但是針對這幾個問題,可能大家一時間也有點懵。今天的文章我們以源碼爲基礎來分析下該如何回答這三個問題。"},{"type":"text","marks":[{"type":"strong"}],"text":"(之前沒閱讀過源碼也沒關係,所有的分析都會貼出源碼及圖解)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"線程池如何按照core、max、queue的順序執行?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"問題思考"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"對於這個問題,很多小夥伴肯定會疑惑:"},{"type":"text","marks":[{"type":"strong"}],"text":"\"別人源碼中寫好的執行流程你爲啥要改?這面試官腦子有病吧......\""}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"這裏來思考一下現實工作場景中是否有這種需求?之前也看到過一份簡歷也寫到過這個問題:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/e1/e1fda2fcc30d39d92e17c8c75bca61ef.png","alt":"場景描述.png","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"一個線程池執行的任務屬於"},{"type":"codeinline","content":[{"type":"text","text":"IO"}]},{"type":"text","text":"密集型,"},{"type":"codeinline","content":[{"type":"text","text":"CPU"}]},{"type":"text","text":"大多屬於閒置狀態,系統資源未充分利用。如果一瞬間來了大量請求,如果線程池數量大於"},{"type":"codeinline","content":[{"type":"text","text":"coreSize"}]},{"type":"text","text":"時,多餘的請求都會放入到等待隊列中。等待着"},{"type":"codeinline","content":[{"type":"text","text":"corePool"}]},{"type":"text","text":"中的線程執行完成後再來執行等待隊列中的任務。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"試想一下,這種場景我們該如何優化?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們可以修改線程池的執行順序爲"},{"type":"text","marks":[{"type":"strong"}],"text":"corePool->maxPool->workQueue"},{"type":"text","text":"。 這樣就能夠充分利用"},{"type":"codeinline","content":[{"type":"text","text":"CPU"}]},{"type":"text","text":"資源,提交的任務會被優先執行。當線程池中線程數量大於"},{"type":"codeinline","content":[{"type":"text","text":"maxSize"}]},{"type":"text","text":"時纔會將任務放入等待隊列中。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"你就說巧不巧?面試官的這個問題顯然是經過認真思考來提問的,這是一個很有意思的問題,下面就一起看看如何解決吧。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"線程池運行流程"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們都知道線程池執行流程是先"},{"type":"codeinline","content":[{"type":"text","text":"corePool"}]},{"type":"text","text":"再"},{"type":"codeinline","content":[{"type":"text","text":"workQueue"}]},{"type":"text","text":",最後纔是"},{"type":"codeinline","content":[{"type":"text","text":"maxPool"}]},{"type":"text","text":"的一個執行流程。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/b2/b29cdd77bba58b56c2748f02fc1e49fb.png","alt":"執行流程.png","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"線程池核心參數"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在回顧下"},{"type":"codeinline","content":[{"type":"text","text":"ThreadPoolExecutor.execute()"}]},{"type":"text","text":"源碼前我們先回顧下線程池中的幾個重要參數:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/91/91b6873d617dff5df839a2971a2d3750.png","alt":"線程池核心參數.png","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們來看下這幾個參數的定義:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"corePoolSize"}]},{"type":"text","text":": 線程池中核心線程數量"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"maximumPoolSize"}]},{"type":"text","text":": 線程池中最大線程數量"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"keepAliveTime"}]},{"type":"text","text":": 非核心的空閒線程等待新任務的時間 "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"unit"}]},{"type":"text","text":": 時間單位。配合"},{"type":"codeinline","content":[{"type":"text","text":"allowCoreThreadTimeOut"}]},{"type":"text","text":"也會清理核心線程池中的線程。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"workQueue"}]},{"type":"text","text":": 基於"},{"type":"codeinline","content":[{"type":"text","text":"Blocking"}]},{"type":"text","text":"的任務隊列,最好選用有界隊列,指定隊列長度"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"threadFactory"}]},{"type":"text","text":": 線程工廠,最好自定義線程工廠,可以自定義每個線程的名稱"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"handler"}]},{"type":"text","text":": 拒絕策略,默認是"},{"type":"codeinline","content":[{"type":"text","text":"AbortPolicy"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"ThreadPoolExecutor.execute()源碼分析"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們可以看下"},{"type":"codeinline","content":[{"type":"text","text":"execute()"}]},{"type":"text","text":"如下:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/98/98b9254065150603fd13454c7fb9124c.png","alt":"execute執行源碼.png","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"接着來分析下執行過程:"}]},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"第一步:"},{"type":"codeinline","content":[{"type":"text","text":"workerCountOf(c)"}]},{"type":"text","text":"時間計算當前線程池中線程的個數,當線程個數小於核心線程數"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"第二步:線程池線程數量大於核心線程數,此時提交的任務會放入"},{"type":"codeinline","content":[{"type":"text","text":"workQueue"}]},{"type":"text","text":"中,使用"},{"type":"codeinline","content":[{"type":"text","text":"offer()"}]},{"type":"text","text":"進行操作"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"第三步:"},{"type":"codeinline","content":[{"type":"text","text":"workQueue.offer()"}]},{"type":"text","text":"執行失敗,新提交的任務會直接執行,"},{"type":"codeinline","content":[{"type":"text","text":"addWorker()"}]},{"type":"text","text":"會判斷如果當前線程池數量大於最大線程數,則執行拒絕策略"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"好了,到了這裏我們都已經很清楚了,關鍵在於第二步和第三步如何交換順序執行呢?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"解決思路"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"仔細想一想,如果修改"},{"type":"codeinline","content":[{"type":"text","text":"workQueue.offer()"}]},{"type":"text","text":"的實現不就可以達到目的了?我們先來畫圖來看一下:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/04/04beb15efd247c9a9fdd869dbca5a28b.png","alt":"問題思路.png","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"現在的問題就在於,如果當前線程池中"},{"type":"codeinline","content":[{"type":"text","text":"coreSize < workCount < maxSize"}]},{"type":"text","text":"時,一定會先執行"},{"type":"codeinline","content":[{"type":"text","text":"offer()"}]},{"type":"text","text":"操作。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們如果修改"},{"type":"codeinline","content":[{"type":"text","text":"offer"}]},{"type":"text","text":"的實現是否可以完成執行順序的更換呢?這裏也是畫圖來展示一下:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/1d/1d50a9600fa58bf7cf66c255d5bebeeb.png","alt":"解決方式.png","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"Dubbo中EagerThreadPool解決方案"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"湊巧"},{"type":"codeinline","content":[{"type":"text","text":"Dubbo"}]},{"type":"text","text":"中也有類似的實現,在"},{"type":"codeinline","content":[{"type":"text","text":"Dubbo"}]},{"type":"text","text":"的"},{"type":"codeinline","content":[{"type":"text","text":"EagerThreadPool"}]},{"type":"text","text":"自定義了一個"},{"type":"codeinline","content":[{"type":"text","text":"BlockingQueue"}]},{"type":"text","text":",在"},{"type":"codeinline","content":[{"type":"text","text":"offer()"}]},{"type":"text","text":"方法中,如果當前線程池數量小於最大線程池時,直接返回"},{"type":"codeinline","content":[{"type":"text","text":"false"}]},{"type":"text","text":",這裏就達到了調節線程池執行順序的目的。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/05/05b68bfe0ff7735eebf7d7afaf069386.png","alt":"dubbo中解決方案.png","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"源碼直達"},{"type":"text","text":":https://github.com/apache/dubbo/blob/master/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueue.java"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"看到這裏一切都真相大白了,解決思路以及方案都很簡單,學會了沒有?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"這個問題背後還隱藏了一些場景的優化、源碼的擴展等等知識,果然是一個值得思考的好問題。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"子線程拋出的異常,主線程能感知到麼?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"問題思考"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"這個問題其實也很容易回答,也僅僅是一個面試題而已,實際工作中子線程的異常不應該由主線程來捕獲。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"針對這個問題,希望大家清楚的是:"},{"type":"text","text":" 我們要明確線程代碼的邊界,異步化過程中,子線程拋出的異常應該由子線程自己去處理,而不是需要主線程感知來協助處理。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"解決方案"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"解決方案很簡單,在虛擬機中,當一個線程如果沒有顯式處理異常而拋出時會將該異常事件報告給該線程對象的 "},{"type":"codeinline","content":[{"type":"text","text":"java.lang.Thread.UncaughtExceptionHandler"}]},{"type":"text","text":" 進行處理,如果線程沒有設置 "},{"type":"codeinline","content":[{"type":"text","text":"UncaughtExceptionHandler"}]},{"type":"text","text":",則默認會把異常棧信息輸出到終端而使程序直接崩潰。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"所以如果我們想在線程意外崩潰時做一些處理就可以通過實現 "},{"type":"codeinline","content":[{"type":"text","text":"UncaughtExceptionHandler"}]},{"type":"text","text":" 來滿足需求。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們使用線程池設置"},{"type":"codeinline","content":[{"type":"text","text":"ThreadFactory"}]},{"type":"text","text":"時可以指定"},{"type":"codeinline","content":[{"type":"text","text":"UncaughtExceptionHandler"}]},{"type":"text","text":",這樣就可以捕獲到子線程拋出的異常了。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"代碼示例"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"具體代碼如下:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"/**\n * 測試子線程異常問題\n *\n * @author wangmeng\n * @date 2020/6/13 18:08\n */\npublic class ThreadPoolExceptionTest {\n\n public static void main(String[] args) throws InterruptedException {\n MyHandler myHandler = new MyHandler();\n ExecutorService execute = new ThreadPoolExecutor(10, 10,\n 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), new ThreadFactoryBuilder().setUncaughtExceptionHandler(myHandler).build());\n\n TimeUnit.SECONDS.sleep(5);\n for (int i = 0; i < 10; i++) {\n execute.execute(new MyRunner());\n }\n }\n\n\n private static class MyRunner implements Runnable {\n @Override\n public void run() {\n int count = 0;\n while (true) {\n count++;\n System.out.println(\"我要開始生產Bug了============\");\n if (count == 10) {\n System.out.println(1 / 0);\n }\n\n if (count == 20) {\n System.out.println(\"這裏是不會執行到的==========\");\n break;\n }\n }\n }\n }\n}\n\nclass MyHandler implements Thread.UncaughtExceptionHandler {\n private final static Logger LOGGER = LoggerFactory.getLogger(MyHandler.class);\n @Override\n public void uncaughtException(Thread t, Throwable e) {\n LOGGER.error(\"threadId = {}, threadName = {}, ex = {}\", t.getId(), t.getName(), e.getMessage());\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"執行結果:"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/d2/d29eada0c31219a97c972ce03467f963.png","alt":"執行結果.png","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"UncaughtExceptionHandler 解析"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們來看下"},{"type":"codeinline","content":[{"type":"text","text":"Thread"}]},{"type":"text","text":"中的內部接口"},{"type":"codeinline","content":[{"type":"text","text":"UncaughtExceptionHandler"}]},{"type":"text","text":":"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public class Thread {\n ......\n /**\n * 當一個線程因未捕獲的異常而即將終止時虛擬機將使用 Thread.getUncaughtExceptionHandler()\n * 獲取已經設置的 UncaughtExceptionHandler 實例,並通過調用其 uncaughtException(...) 方\n * 法而傳遞相關異常信息。\n * 如果一個線程沒有明確設置其 UncaughtExceptionHandler,則將其 ThreadGroup 對象作爲其\n * handler,如果 ThreadGroup 對象對異常沒有什麼特殊的要求,則 ThreadGroup 會將調用轉發給\n * 默認的未捕獲異常處理器(即 Thread 類中定義的靜態未捕獲異常處理器對象)。\n *\n * @see #setDefaultUncaughtExceptionHandler\n * @see #setUncaughtExceptionHandler\n * @see ThreadGroup#uncaughtException\n */\n @FunctionalInterface\n public interface UncaughtExceptionHandler {\n /**\n * 未捕獲異常崩潰時回調此方法\n */\n void uncaughtException(Thread t, Throwable e);\n }\n\n /**\n * 靜態方法,用於設置一個默認的全局異常處理器。\n */\n public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {\n defaultUncaughtExceptionHandler = eh;\n }\n\n /**\n * 針對某個 Thread 對象的方法,用於對特定的線程進行未捕獲的異常處理。\n */\n public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {\n checkAccess();\n uncaughtExceptionHandler = eh;\n }\n\n /**\n * 當 Thread 崩潰時會調用該方法獲取當前線程的 handler,獲取不到就會調用 group(handler 類型)。\n * group 是 Thread 類的 ThreadGroup 類型屬性,在 Thread 構造中實例化。\n */\n public UncaughtExceptionHandler getUncaughtExceptionHandler() {\n return uncaughtExceptionHandler != null ?\n uncaughtExceptionHandler : group;\n }\n\n /**\n * 線程全局默認 handler。\n */\n public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() {\n return defaultUncaughtExceptionHandler;\n }\n ......\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"部分內容參考自:https://mp.weixin.qq.com/s/ghnNQnpou6-NemhFjpl4Jg"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"線程池發生了異常改怎樣處理?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"線程池中線程運行過程中出現了異常該怎樣處理呢?線程池提交任務有兩種方式,分別是"},{"type":"codeinline","content":[{"type":"text","text":"execute()"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"submit()"}]},{"type":"text","text":",這裏會依次說明。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"ThreadPoolExecutor.runWorker()實現"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"不管是使用"},{"type":"codeinline","content":[{"type":"text","text":"execute()"}]},{"type":"text","text":"還是"},{"type":"codeinline","content":[{"type":"text","text":"submit()"}]},{"type":"text","text":"提交任務,最終都會執行到"},{"type":"codeinline","content":[{"type":"text","text":"ThreadPoolExecutor.runWorker()"}]},{"type":"text","text":",我們來看下源碼(源碼基於JDK1.8):"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/45/4533fca9daee72cebfcb29d680b46438.png","alt":"runWorker().png","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們看到在執行"},{"type":"codeinline","content":[{"type":"text","text":"task.run()"}]},{"type":"text","text":"時,出現異常會直接向上拋出,這裏處理的最好的方式就是在我們業務代碼中使用"},{"type":"codeinline","content":[{"type":"text","text":"try...catch()"}]},{"type":"text","text":"來捕獲異常。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"FutureTask.run()實現"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"如果我們使用"},{"type":"codeinline","content":[{"type":"text","text":"submit()"}]},{"type":"text","text":"來提交任務,在"},{"type":"codeinline","content":[{"type":"text","text":"ThreadPoolExecutor.runWorker()"}]},{"type":"text","text":"方法執行時最終會調用到"},{"type":"codeinline","content":[{"type":"text","text":"FutureTask.run()"}]},{"type":"text","text":"方法裏面去,不清楚的小夥伴也可以看下我之前的文章:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"[線程池續:你必須要知道的線程池submit()實現原理之FutureTask!][2]"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/c3/c3b06c75775d46854ba38c4569fe3943.png","alt":"FutureTask.run().png","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"這裏可以看到,如果業務代碼拋出異常後,會被"},{"type":"codeinline","content":[{"type":"text","text":"catch"}]},{"type":"text","text":"捕獲到,然後調用"},{"type":"codeinline","content":[{"type":"text","text":"setExeception()"}]},{"type":"text","text":"方法:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/f9/f96ec090d886b19bd34f380cce97564f.png","alt":"FutureTask.setException().png","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"可以看到其實類似於直接吞掉了,當我們調用"},{"type":"codeinline","content":[{"type":"text","text":"get()"}]},{"type":"text","text":"方法的時候異常信息會包裝到FutureTask內部的變量outcome中,我們也會獲取到對應的異常信息。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在"},{"type":"codeinline","content":[{"type":"text","text":"ThreadPoolExecutor.runWorker()"}]},{"type":"text","text":"最後"},{"type":"codeinline","content":[{"type":"text","text":"finally"}]},{"type":"text","text":"中有一個"},{"type":"codeinline","content":[{"type":"text","text":"afterExecute()"}]},{"type":"text","text":"鉤子方法,如果我們重寫了"},{"type":"codeinline","content":[{"type":"text","text":"afterExecute()"}]},{"type":"text","text":"方法,就可以獲取到子線程拋出的具體異常信息"},{"type":"codeinline","content":[{"type":"text","text":"Throwable"}]},{"type":"text","text":"了。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"結論"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"對於線程池、包括線程的異常處理推薦以下方式:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"直接使用"},{"type":"codeinline","content":[{"type":"text","text":"try/catch"}]},{"type":"text","text":",這個也是最推薦的方式"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"在我們構造線程池的時候,重寫"},{"type":"codeinline","content":[{"type":"text","text":"uncaughtException()"}]},{"type":"text","text":"方法,上面示例代碼也有提到:"}]}]}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public class ThreadPoolExceptionTest {\n\n public static void main(String[] args) throws InterruptedException {\n MyHandler myHandler = new MyHandler();\n ExecutorService execute = new ThreadPoolExecutor(10, 10,\n 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), new ThreadFactoryBuilder().setUncaughtExceptionHandler(myHandler).build());\n\n TimeUnit.SECONDS.sleep(5);\n for (int i = 0; i < 10; i++) {\n execute.execute(new MyRunner());\n }\n }\n}\n\nclass MyHandler implements Thread.UncaughtExceptionHandler {\n private final static Logger LOGGER = LoggerFactory.getLogger(MyHandler.class);\n @Override\n public void uncaughtException(Thread t, Throwable e) {\n LOGGER.error(\"threadId = {}, threadName = {}, ex = {}\", t.getId(), t.getName(), e.getMessage());\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"3 直接重寫"},{"type":"codeinline","content":[{"type":"text","text":"afterExecute()"}]},{"type":"text","text":"方法,感知異常細節"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"總結"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"這篇文章到這裏就結束了,不知道小夥伴們有沒有一些感悟或收穫?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通過這幾個面試問題,我也深刻的感受到學習知識要多思考,看源碼的過程中要多設置一些場景,這樣纔會收穫更多。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"[1]:https://xie.infoq.cn/article/6bd3b2d377832c5c2752f9a66"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"[2]:https://xie.infoq.cn/article/316d14bf0693470689f48ffa7"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/ce/ce66cf44e1c5e8adae71e260b34e4139.png","alt":"原創乾貨分享.png","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章