面试官:线程池如何按照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}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章