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

标签 java multithreading concurrency interrupt executorservice

我有一个任务,我计划通过 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/

相关文章:

Java 并发 - 内联初始化的非最终字段和安全发布

c++ - MFT 的大小与 MFT 的解析

java - 如何修复 CosmosDB for MongoDB api 上的 'Projection operator not supported' 错误?

java - 检测 JavaFX WebView 中的 URL 更改

java - Gradle 多项目 - 在 "clean"之前为每个 java 库项目应用 "jar"任务

c++ - boost 线程中的 "too few arguments to function"

concurrency - 从 mpsc UnboundedReceiver 读取所有可用消息,而不会不必要地阻塞

concurrency - clojure ref 的奇怪行为

scala - 如何制作 scala actor 'wait for the signal' 但不丢失任何消息?

java - 我的井字游戏方法之一出错