代码之家  ›  专栏  ›  技术社区  ›  Justin

ScheduledExecutorService工作线程在FutureTask之后保留中断状态。取消(真)

  •  4
  • Justin  · 技术社区  · 14 年前

    我有一个计划定期运行的任务 ScheduledThreadPoolExecutor.scheduleAtFixedRate(task, rate, ...) . 用户可以手动取消此任务,这将调用 ScheduledFuture.cancel(true) . 出于某种原因,可能取决于何时取消此任务,工作线程(执行器用于运行任务)在任务的Run()方法退出后仍然处于中断状态。

    我会认为,工作线程(从一个池中获得并重用)将在使用现有的钩子(通过)启动新任务之前清除它们的中断状态。 ThreadPoolExecutor.beforeExecute() ThreadPoolExecutor.afterExecute() ). 但在默认实现中不会这样做。

    我有两个问题:

    • 如何使工作线程处于设置中断状态的状态?
    • 为什么默认实现在启动新任务之前不清除中断状态?
    2 回复  |  直到 14 年前
        1
  •  5
  •   Tim Bender    14 年前
    * 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();
    

    如您所见,只要执行器不关闭,中断状态就会从工作线程中清除。

        2
  •  -1
  •   Bill Horvath    14 年前

    用户如何中断线程?如果他们使用的是UI组件,那么您的问题可能是由于事件分派线程的同步问题造成的。