在FutureTask.cancel之后,ScheduledExecutorService工作线程保持中断状态(true)

Jus*_*tin 4 java concurrency multithreading interrupt executorservice

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

虽然工作线程(从池中取出并重用)在使用现有钩子(通过ThreadPoolExecutor.beforeExecute()ThreadPoolExecutor.afterExecute())开始新任务之前将会清除其中断状态.但它不会在默认实现中执行此操作.

我有两个问题:

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

Tim*_*der 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?
Run Code Online (Sandbox Code Playgroud)

答案是:

  • 它不会处于中断状态.
  • 实施确实如此,但你没有找到正确的位置

从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();
Run Code Online (Sandbox Code Playgroud)

如您所见,只要执行程序没有关闭,就会从工作线程中清除中断状态.