我有一项任务,我计划通过ScheduledThreadPoolExecutor.scheduleAtFixedRate(task, rate, ...)定期运行。用户可以手动取消此任务,调用ScheduledFuture.cancel(true)。出于某种原因,可能取决于它们取消此任务的时间,在我的任务的run()方法退出后,工作线程(执行程序用来运行我的任务)似乎保持中断状态。
我希望工作线程(从池中获取并重用)在使用现有钩子(通过ThreadPoolExecutor.beforeExecute()或ThreadPoolExecutor.afterExecute())开始新任务之前将清除其中断状态。但它在默认实现中不会这样做。
我有两个问题:
答案 0 :(得分:5)
* 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();
如您所见,只要执行程序没有关闭,就会从工作线程中清除中断状态。
答案 1 :(得分:-1)
用户如何中断线程?如果他们使用的是UI组件,则问题可能是由于事件派发线程的同步问题。