4

我有一个任务,我计划通过ScheduledThreadPoolExecutor.scheduleAtFixedRate(task, rate, ...)定期运行。用户可以手动取消此任务,这会调用ScheduledFuture.cancel(true)。出于某种原因,可能取决于他们何时取消此任务,工作线程(执行程序用于运行我的任务)在我的任务的 run() 方法退出后似乎保持中断状态。

尽管工作线程(从池中获取并重用)会在使用现有钩子(通过ThreadPoolExecutor.beforeExecute()ThreadPoolExecutor.afterExecute())开始新任务之前清除其中断状态。但它在默认实现中不这样做。

我有两个问题:

  • 工作线程怎么会处于设置了中断状态的状态?
  • 为什么默认实现在开始新任务之前不清除中断状态?
4

2 回答 2

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();

正如你所看到的,只要执行器没有关闭,中断状态就会从工作线程中清除。

于 2010-11-10T21:52:30.923 回答
-1

用户如何中断线程?如果他们使用 UI 组件,您的问题可能是由于事件调度线程的同步问题。

于 2010-11-10T20:57:31.200 回答