【问题标题】:Which one of these two methods should I use to stop correctly a scheduled thread?我应该使用这两种方法中的哪一种来正确停止计划的线程?
【发布时间】:2019-09-11 15:40:56
【问题描述】:

我创建了一个简单的任务,每两分钟运行一次,一旦布尔值变为真,我想停止它。

ScheduledExecutorService scheduledxecutor = Executors.newScheduledThreadPool(1);

ScheduledFuture<?> scheduledFuture = scheduledExecutor.scheduleAtFixedRate(drawRunnable , 0, 2, TimeUnit.MINUTES);

我一直潜伏在 stackoverflow 周围,基本上发现我需要使用 scheduledFuture.cancel(false)scheduledExecutor.shutdown()

我应该使用哪一个?

【问题讨论】:

    标签: java multithreading scheduled-tasks scheduledexecutorservice


    【解决方案1】:

    scheduledExecutor.shutdown() 是更好的选择,因为它优雅地开始关闭所有提交的任务,而 scheduleFuture.cancel(false) 仅处理该特定任务。

    【讨论】:

      【解决方案2】:

      如果执行器服务没有任务,它仍然活着并准备再次使用。一些资源仍然被阻止。如果您仅将执行程序用于此单个任务,那么最好使用scheduledExecutor.shutdown()。它将等到当前任务完成,不会开始新的任务。所以即使任务正在运行,调用它也是安全的。

      但是如果你向这个执行器服务添加更多的任务,最好只取消一个特定的任务。然后,您将确保不会取消任何其他任务。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-03
        • 2018-06-27
        • 1970-01-01
        相关资源
        最近更新 更多