gpt4 book ai didi

java - ThreadPoolExecutor 如何中断空闲线程?

转载 作者:行者123 更新时间:2023-11-29 06:00:20 25 4
gpt4 key购买 nike

刚刚翻了一下ThreadPoolExecutor的源码,发现一旦达到keepAliveTime的设定值,allowCoreThreadTimeOut为true,它就会中断所有空闲的worker。

我有点奇怪它只能在 runState >= SHUTDOWN 时调用中断方法:

下面的代码来自ThreadPoolExecutor的方法getTask()

Runnable getTask() {
...
if (workerCanExit()) {
if (runState >= SHUTDOWN) // Wake up others
interruptIdleWorkers();
return null;
}
}

这是否意味着所有空闲线程只能在 runState >= SHUTDOWN(SHUTDOWN、STOP 或 TERMINATED)时被中断?也就是说,当状态为 RUNNING 时,它们不会被中断。

最佳答案

你是对的。 ThreadPoolExecutor 中的此 getTask() 方法被调用以获取要运行的工作线程的下一个任务。此代码块仅在方法调用未识别任何要执行的 Runnable 任务时执行。因此,如果没有发现要执行的内容,它必须检查关闭状态。

来自 workerCanExit() 的 java 文档

Check whether a worker thread that fails to get a task can exit. We allow a worker thread to die if the pool is stopping, or the queue is empty, or there is at least one thread to handle possibly non-empty queue, even if core timeouts are allowed.

关于java - ThreadPoolExecutor 如何中断空闲线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10384868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com