停止 ScheduledThreadPoolExecutor 的最佳方法

Best way to stop a ScheduledThreadPoolExecutor

我正在使用一个 ScheduledThreadPoolExecutor 来管理多个任务,并希望添加停止它们的选项。
我了解常规执行程序服务上 shutdown 和 shutdownNow 之间的区别,并且有兴趣了解它将如何影响 ScheduledThreadPoolExecutor 中的任务 - 其中任务也被安排为定​​期 运行。
给定一个 运行ning ScheduledThreadPoolExecutor 有两个 运行ning 任务,一次任务计划在将来 运行,任务计划为 运行 以固定间隔(每 X 分钟一次)。 实施以下 "commands" 的最佳方法是什么:

  1. 现在停止一切。立即停止所有 运行ning 任务,不要 运行 任何已安排但尚未开始的任务。
  2. 目前 运行ning 个线程可以根据需要完成。不要 运行 任何已安排但尚未开始的任务。

您可以使用

配置它

所以你的两个案例是

  1. 致电shutdownNow
  2. 将继续策略设置为 false,然后调用 shutdown
  1. 现在停止一切。立即停止所有 运行ning 任务,不要 运行 任何已安排但尚未开始的任务。

You can use the method : public List<Runnable> shutdownNow() , but please note that the currently executing threads may not immediately terminate. If you want to do that, then you have to find a way to signal a killing of the process via a separate thread or something.

From the Javadocs: There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. This implementation cancels tasks via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

  1. 目前 运行ning 个线程可以根据需要完成。不要 运行 任何已安排但尚未开始的任务。

This can be achieved by using the method: public void shutdown()

From the Javadocs: If the ExecuteExistingDelayedTasksAfterShutdownPolicy has been set false, existing delayed tasks whose delays have not yet elapsed are cancelled. And unless the ContinueExistingPeriodicTasksAfterShutdownPolicy has been set true, future executions of existing periodic tasks will be cancelled.