你能解释一下,为什么在 ScheduledThreadPoolExecutor
javadoc 中是这样的:
Additionally, it is almost never a good idea to set
corePoolSize
to zero or useallowCoreThreadTimeOut
because this may leave the pool without threads to handle tasks once they become eligible to run.
我尝试分析当必须执行新任务时如何在此线程池中创建新线程,并且我认为 javadoc 中描述的问题不应该发生。
最佳答案
线程池尽量使工作线程数等于corePoolSize
,通过缓存线程来提高效率。允许核心线程超时与此目的相反。如果允许核心线程超时,则会执行新任务,但会导致重复创建和销毁工作线程。
如果设置allowCoreThreadTimeOut = true
,那么工作线程在任务队列中找不到任务且超时后,即使工作线程数量小于corePoolSize<,也会被销毁
。所以,如果此时提交新的任务,线程池就必须创建新的线程。
如果设置allowCoreThreadTimeOut = false
,那么工作线程在任务队列中没有发现任务且工作线程数量小于corePoolSize
后,不会被销毁并继续等待新任务。
关于java - 使用 ScheduledThreadPoolExecutor 允许核心线程超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48424367/