【高并发】深度解析ScheduledThreadPoolExecutor类的源代码

{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"大家好,我是冰河~~","attrs":{}}]},{"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":"在【高并发专题】的专栏中,我们深度分析了ThreadPoolExecutor类的源代码,而ScheduledThreadPoolExecutor类是ThreadPoolExecutor类的子类。今天我们就来一起手撕ScheduledThreadPoolExecutor类的源代码。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"构造方法","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们先来看下ScheduledThreadPoolExecutor的构造方法,源代码如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public ScheduledThreadPoolExecutor(int corePoolSize) {\n super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue());\n}\n\npublic ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) {\n super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,\n new DelayedWorkQueue(), threadFactory);\n}\n\npublic ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler) {\n super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,\n new DelayedWorkQueue(), handler);\n}\n\npublic ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) {\n super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,\n new DelayedWorkQueue(), threadFactory, handler);\n}\n","attrs":{}}]},{"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":"从代码结构上来看,ScheduledThreadPoolExecutor类是ThreadPoolExecutor类的子类,ScheduledThreadPoolExecutor类的构造方法实际上调用的是ThreadPoolExecutor类的构造方法。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"schedule方法","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"接下来,我们看一下ScheduledThreadPoolExecutor类的schedule方法,源代码如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public ScheduledFuture> schedule(Runnable command, long delay, TimeUnit unit) {\n //如果传递的Runnable对象和TimeUnit时间单位为空\n //抛出空指针异常\n if (command == null || unit == null)\n throw new NullPointerException();\n //封装任务对象,在decorateTask方法中直接返回ScheduledFutureTask对象\n RunnableScheduledFuture> t = decorateTask(command, new ScheduledFutureTask(command, null, triggerTime(delay, unit)));\n //执行延时任务\n delayedExecute(t);\n //返回任务\n return t;\n}\n\npublic ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) \n //如果传递的Callable对象和TimeUnit时间单位为空\n //抛出空指针异常\n if (callable == null || unit == null)\n throw new NullPointerException();\n //封装任务对象,在decorateTask方法中直接返回ScheduledFutureTask对象\n RunnableScheduledFuture t = decorateTask(callable,\n new ScheduledFutureTask(callable, triggerTime(delay, unit)));\n //执行延时任务\n delayedExecute(t);\n //返回任务\n return t;\n}\n","attrs":{}}]},{"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":"从源代码可以看出,ScheduledThreadPoolExecutor类提供了两个重载的schedule方法,两个schedule方法的第一个参数不同。可以传递Runnable接口对象,也可以传递Callable接口对象。在方法内部,会将Runnable接口对象和Callable接口对象封装成RunnableScheduledFuture对象,本质上就是封装成ScheduledFutureTask对象。并通过delayedExecute方法来执行延时任务。","attrs":{}}]},{"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":"在源代码中,我们看到两个schedule都调用了decorateTask方法,接下来,我们就看看decorateTask方法。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"decorateTask方法","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"decorateTask方法源代码如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"protected RunnableScheduledFuture decorateTask(Runnable runnable, RunnableScheduledFuture task) {\n return task;\n}\n\nprotected RunnableScheduledFuture decorateTask(Callable callable, RunnableScheduledFuture task) {\n return task;\n}\n","attrs":{}}]},{"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":"通过源码可以看出decorateTask方法的实现比较简单,接收一个Runnable接口对象或者Callable接口对象和封装的RunnableScheduledFuture任务,两个方法都是将RunnableScheduledFuture任务直接返回。在ScheduledThreadPoolExecutor类的子类中可以重写这两个方法。","attrs":{}}]},{"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":"接下来,我们继续看下scheduleAtFixedRate方法。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"scheduleAtFixedRate方法","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"scheduleAtFixedRate方法源代码如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public ScheduledFuture> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {\n //传入的Runnable对象和TimeUnit为空,则抛出空指针异常\n if (command == null || unit == null)\n throw new NullPointerException();\n //如果执行周期period传入的数值小于或者等于0\n //抛出非法参数异常\n if (period <= 0)\n throw new IllegalArgumentException();\n //将Runnable对象封装成ScheduledFutureTask任务,\n //并设置执行周期\n ScheduledFutureTask sft =\n new ScheduledFutureTask(command, null, triggerTime(initialDelay, unit), unit.toNanos(period));\n //调用decorateTask方法,本质上还是直接返回ScheduledFutureTask对象\n RunnableScheduledFuture t = decorateTask(command, sft);\n //设置执行的任务\n sft.outerTask = t;\n //执行延时任务\n delayedExecute(t);\n //返回执行的任务\n return t;\n}\n","attrs":{}}]},{"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":"通过源码可以看出,scheduleAtFixedRate方法将传递的Runnable对象封装成ScheduledFutureTask任务对象,并设置了执行周期,下一次的执行时间相对于上一次的执行时间来说,加上了period时长,时长的具体单位由TimeUnit决定。采用固定的频率来执行定时任务。","attrs":{}}]},{"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":"ScheduledThreadPoolExecutor类中另一个定时调度任务的方法是scheduleWithFixedDelay方法,接下来,我们就一起看看scheduleWithFixedDelay方法。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"scheduleWithFixedDelay方法","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"scheduleWithFixedDelay方法的源代码如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public ScheduledFuture> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {\n //传入的Runnable对象和TimeUnit为空,则抛出空指针异常\n if (command == null || unit == null)\n throw new NullPointerException();\n //任务延时时长小于或者等于0,则抛出非法参数异常\n if (delay <= 0)\n throw new IllegalArgumentException();\n //将Runnable对象封装成ScheduledFutureTask任务\n //并设置固定的执行周期来执行任务\n ScheduledFutureTask sft =\n new ScheduledFutureTask(command, null,triggerTime(initialDelay, unit), unit.toNanos(-delay));\n //调用decorateTask方法,本质上直接返回ScheduledFutureTask任务\n RunnableScheduledFuture t = decorateTask(command, sft);\n //设置执行的任务\n sft.outerTask = t;\n //执行延时任务\n delayedExecute(t);\n //返回任务\n return t;\n}\n","attrs":{}}]},{"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":"从scheduleWithFixedDelay方法的源代码,我们可以看出在将Runnable对象封装成ScheduledFutureTask时,设置了执行周期,但是此时设置的执行周期与scheduleAtFixedRate方法设置的执行周期不同。此时设置的执行周期规则为:下一次任务执行的时间是上一次任务完成的时间加上delay时长,时长单位由TimeUnit决定。也就是说,具体的执行时间不是固定的,但是执行的周期是固定的,整体采用的是相对固定的延迟来执行定时任务。","attrs":{}}]},{"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":"如果大家细心的话,会发现在scheduleWithFixedDelay方法中设置执行周期时,传递的delay值为负数,如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"ScheduledFutureTask sft =\n new ScheduledFutureTask(command, null, triggerTime(initialDelay, unit), unit.toNanos(-delay));\n","attrs":{}}]},{"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":"这里的负数表示的是相对固定的延迟。","attrs":{}}]},{"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":"在ScheduledFutureTask类中,存在一个setNextRunTime方法,这个方法会在run方法执行完任务后调用,这个方法更能体现scheduleAtFixedRate方法和scheduleWithFixedDelay方法的不同,setNextRunTime方法的源码如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"private void setNextRunTime() {\n //距离下次执行任务的时长\n long p = period;\n //固定频率执行,\n //上次执行任务的时间\n //加上任务的执行周期\n if (p > 0)\n time += p;\n //相对固定的延迟\n //使用的是系统当前时间\n //加上任务的执行周期\n else\n time = triggerTime(-p);\n}\n","attrs":{}}]},{"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":"在setNextRunTime方法中通过对下次执行任务的时长进行判断来确定是固定频率执行还是相对固定的延迟。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"triggerTime方法","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在ScheduledThreadPoolExecutor类中提供了两个triggerTime方法,用于获取下一次执行任务的具体时间。triggerTime方法的源码如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"private long triggerTime(long delay, TimeUnit unit) {\n return triggerTime(unit.toNanos((delay < 0) ? 0 : delay));\n}\n\nlong triggerTime(long delay) {\n return now() +\n ((delay < (Long.MAX_VALUE >> 1)) ? delay : overflowFree(delay));\n}\n","attrs":{}}]},{"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":"这两个triggerTime方法的代码比较简单,就是获取下一次执行任务的具体时间。有一点需要注意的是:delay < (Long.MAX_VALUE >> 1判断delay的值是否小于Long.MAX_VALUE的一半,如果小于Long.MAX_VALUE值的一半,则直接返回delay,否则需要处理溢出的情况。","attrs":{}}]},{"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":"我们看到在triggerTime方法中处理防止溢出的逻辑使用了overflowFree方法,接下来,我们就看看overflowFree方法的实现。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"overflowFree方法","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"overflowFree方法的源代码如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"private long overflowFree(long delay) {\n //获取队列中的节点\n Delayed head = (Delayed) super.getQueue().peek();\n //获取的节点不为空,则进行后续处理\n if (head != null) {\n //从队列节点中获取延迟时间\n long headDelay = head.getDelay(NANOSECONDS);\n //如果从队列中获取的延迟时间小于0,并且传递的delay\n //值减去从队列节点中获取延迟时间小于0\n if (headDelay < 0 && (delay - headDelay < 0))\n //将delay的值设置为Long.MAX_VALUE + headDelay\n delay = Long.MAX_VALUE + headDelay;\n }\n //返回延迟时间\n return delay;\n}\n","attrs":{}}]},{"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":"通过对overflowFree方法的源码分析,可以看出overflowFree方法本质上就是为了限制队列中的所有节点的延迟时间在Long.MAX_VALUE值之内,防止在ScheduledFutureTask类中的compareTo方法中溢出。","attrs":{}}]},{"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":"ScheduledFutureTask类中的compareTo方法的源码如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public int compareTo(Delayed other) {\n if (other == this) // compare zero if same object\n return 0;\n if (other instanceof ScheduledFutureTask) {\n ScheduledFutureTask> x = (ScheduledFutureTask>)other;\n long diff = time - x.time;\n if (diff < 0)\n return -1;\n else if (diff > 0)\n return 1;\n else if (sequenceNumber < x.sequenceNumber)\n return -1;\n else\n return 1;\n }\n long diff = getDelay(NANOSECONDS) - other.getDelay(NANOSECONDS);\n return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;\n}\n","attrs":{}}]},{"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":"compareTo方法的主要作用就是对各延迟任务进行排序,距离下次执行时间靠前的任务就排在前面。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"delayedExecute方法","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"delayedExecute方法是ScheduledThreadPoolExecutor类中延迟执行任务的方法,源代码如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"private void delayedExecute(RunnableScheduledFuture> task) {\n //如果当前线程池已经关闭\n //则执行线程池的拒绝策略\n if (isShutdown())\n reject(task);\n //线程池没有关闭\n else {\n //将任务添加到阻塞队列中\n super.getQueue().add(task);\n //如果当前线程池是SHUTDOWN状态\n //并且当前线程池状态下不能执行任务\n //并且成功从阻塞队列中移除任务\n if (isShutdown() &&\n !canRunInCurrentRunState(task.isPeriodic()) &&\n remove(task))\n //取消任务的执行,但不会中断执行中的任务\n task.cancel(false);\n else\n //调用ThreadPoolExecutor类中的ensurePrestart()方法\n ensurePrestart();\n }\n}\n","attrs":{}}]},{"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":"可以看到在delayedExecute方法内部调用了canRunInCurrentRunState方法,canRunInCurrentRunState方法的源码实现如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"boolean canRunInCurrentRunState(boolean periodic) {\n return isRunningOrShutdown(periodic ? continueExistingPeriodicTasksAfterShutdown : executeExistingDelayedTasksAfterShutdown);\n}\n","attrs":{}}]},{"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":"可以看到canRunInCurrentRunState方法的逻辑比较简单,就是判断线程池当前状态下能够执行任务。","attrs":{}}]},{"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":"另外,在delayedExecute方法内部还调用了ThreadPoolExecutor类中的ensurePrestart()方法,接下来,我们看下ThreadPoolExecutor类中的ensurePrestart()方法的实现,如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"void ensurePrestart() {\n int wc = workerCountOf(ctl.get());\n if (wc < corePoolSize)\n addWorker(null, true);\n else if (wc == 0)\n addWorker(null, false);\n}\n","attrs":{}}]},{"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":"在ThreadPoolExecutor类中的ensurePrestart()方法中,首先获取当前线程池中线程的数量,如果线程数量小于corePoolSize则调用addWorker方法传递null和true,如果线程数量为0,则调用addWorker方法传递null和false。","attrs":{}}]},{"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":"关于addWork()方法的源码解析,大家可以参考【高并发专题】中的《","attrs":{}},{"type":"link","attrs":{"href":"https://blog.csdn.net/l1028386804/article/details/104480010","title":"","type":null},"content":[{"type":"text","text":"高并发之——通过ThreadPoolExecutor类的源码深度解析线程池执行任务的核心流程","attrs":{}}]},{"type":"text","text":"》一文,这里,不再赘述。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"reExecutePeriodic方法","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"reExecutePeriodic方法的源代码如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"void reExecutePeriodic(RunnableScheduledFuture> task) {\n //线程池当前状态下能够执行任务\n if (canRunInCurrentRunState(true)) {\n //将任务放入队列\n super.getQueue().add(task);\n //线程池当前状态下不能执行任务,并且成功移除任务\n if (!canRunInCurrentRunState(true) && remove(task))\n //取消任务\n task.cancel(false);\n else\n //调用ThreadPoolExecutor类的ensurePrestart()方法\n ensurePrestart();\n }\n}\n","attrs":{}}]},{"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":"总体来说reExecutePeriodic方法的逻辑比较简单,但是,这里需要注意和delayedExecute方法的不同点:调用reExecutePeriodic方法的时候已经执行过一次任务,所以,并不会触发线程池的拒绝策略;传入reExecutePeriodic方法的任务一定是周期性的任务。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"onShutdown方法","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"onShutdown方法是ThreadPoolExecutor类中的钩子函数,它是在ThreadPoolExecutor类中的shutdown方法中调用的,而在ThreadPoolExecutor类中的onShutdown方法是一个空方法,如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"void onShutdown() {\n}\n","attrs":{}}]},{"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":"ThreadPoolExecutor类中的onShutdown方法交由子类实现,所以ScheduledThreadPoolExecutor类覆写了onShutdown方法,实现了具体的逻辑,ScheduledThreadPoolExecutor类中的onShutdown方法的源码实现如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"@Override\nvoid onShutdown() {\n //获取队列\n BlockingQueue q = super.getQueue();\n //在线程池已经调用shutdown方法后,是否继续执行现有延迟任务\n boolean keepDelayed = getExecuteExistingDelayedTasksAfterShutdownPolicy();\n //在线程池已经调用shutdown方法后,是否继续执行现有定时任务\n boolean keepPeriodic = getContinueExistingPeriodicTasksAfterShutdownPolicy();\n //在线程池已经调用shutdown方法后,不继续执行现有延迟任务和定时任务\n if (!keepDelayed && !keepPeriodic) {\n //遍历队列中的所有任务\n for (Object e : q.toArray())\n //取消任务的执行\n if (e instanceof RunnableScheduledFuture>)\n ((RunnableScheduledFuture>) e).cancel(false);\n //清空队列\n q.clear();\n }\n //在线程池已经调用shutdown方法后,继续执行现有延迟任务和定时任务\n else {\n //遍历队列中的所有任务\n for (Object e : q.toArray()) {\n //当前任务是RunnableScheduledFuture类型\n if (e instanceof RunnableScheduledFuture) {\n //将任务强转为RunnableScheduledFuture类型\n RunnableScheduledFuture> t = (RunnableScheduledFuture>)e;\n //在线程池调用shutdown方法后不继续的延迟任务或周期任务\n //则从队列中删除并取消任务\n if ((t.isPeriodic() ? !keepPeriodic : !keepDelayed) ||\n t.isCancelled()) {\n if (q.remove(t))\n t.cancel(false);\n }\n }\n }\n }\n //最终调用tryTerminate()方法\n tryTerminate();\n}\n","attrs":{}}]},{"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":"ScheduledThreadPoolExecutor类中的onShutdown方法的主要逻辑就是先判断线程池调用shutdown方法后,是否继续执行现有的延迟任务和定时任务,如果不再执行,则取消任务并清空队列;如果继续执行,将队列中的任务强转为RunnableScheduledFuture对象之后,从队列中删除并取消任务。大家需要好好理解这两种处理方式。最后调用ThreadPoolExecutor类的tryTerminate方法。有关ThreadPoolExecutor类的tryTerminate方法的源码解析,大家可以参考【高并发专题】中的《","attrs":{}},{"type":"link","attrs":{"href":"https://xie.infoq.cn/article/bc67b560692368622ede9ea76","title":"","type":null},"content":[{"type":"text","text":"高并发之——通过源码深度分析线程池中Worker线程的执行流程","attrs":{}}]},{"type":"text","text":"》一文,这里不再赘述。","attrs":{}}]},{"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":"至此,ScheduledThreadPoolExecutor类中的核心方法的源代码,我们就分析完了。","attrs":{}}]},{"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","attrs":{}}],"text":"好了,今天就到这儿吧,我是冰河,我们下期见~~","attrs":{}}]}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章