https://www.zhihu.com/question/29971107
<noscript>
</noscript>

</figure>
在向线程池提交任务时,如果核心线程已满、队列已满且线程池最大线程数未满时,就会创建出题主所说的“大于corePoolsize的多出线程”。
这里通过源代码来说明下(jdk1.8.0_101):
线程池的execute方法实现:
<figure>
<noscript>
</noscript>

</figure>
再来说说keepAliveTime,这个参数是用来控制,超出corePoolSize的线程在这个时间还没有可执行的任务时,则自动退出(线程销毁)
口说无凭,还是源代码来验证:
上边说到了调用addWorker创建线程,这里看看addWorker方法
<figure>
<noscript>
</noscript>

</figure>
线程启动后就会调用Worker对象的run方法:
<figure>
<noscript>
</noscript>

</figure>
runWoker方法就是线程从队列里拿任务开始干活,如果等了keepAliveTime还没有任务并且线程数大于coreSizePoll,则线程就会执行完毕退出。
<figure>
<noscript>
</noscript>

</figure>
接下来再看看getTask方法,这里就是判断keepAliveTime的关键了
<figure>
<noscript>
</noscript>

</figure>
到这里,题主应该能明白什么时候创建线程,线程什么时候退出了。
网友评论