我有一个任务,我计划通过 ScheduledThreadPoolExecutor.scheduleAtFixedRate(task, rate, ...) 定期运行.用户可以手动取消此任务,调用 ScheduledFuture.cancel(true) .出于某种原因,可能取决于他们何时取消此任务,工作线程(执行程序用来运行我的任务)在我的任务的 run() 方法退出后似乎仍处于中断状态。
我本来希望工作线程(从池中取出并重用)在使用现有 Hook (通过 ThreadPoolExecutor.beforeExecute() 或 ThreadPoolExecutor.afterExecute() )开始新任务之前清除其中断状态。但它在默认实现中不这样做。
我有两个问题:
- 工作线程如何处于设置中断状态的状态?
- 为什么默认实现在开始新任务之前不清除中断状态?
最佳答案
* How is it that the worker thread is left in a state where the interrupt status is set? * Why does the default implementation not clear the interrupt status before starting a new task?
答案是:
- 它不会处于中断状态。
- 实现了,但你没有找对地方
来自 Oracle 库代码:
/*
* Ensure that unless pool is stopping, this thread
* does not have its interrupt set. This requires a
* double-check of state in case the interrupt was
* cleared concurrently with a shutdownNow -- if so,
* the interrupt is re-enabled.
*/
if (runState < STOP &&
Thread.interrupted() &&
runState >= STOP)
thread.interrupt();
如您所见,只要执行程序未关闭,中断状态就会从工作线程中清除。
关于java - ScheduledExecutorService 工作线程在 FutureTask.cancel(true) 之后保持中断状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4148845/