【问题标题】:ScheduledExecutorService, how to stop action without stopping executor?ScheduledExecutorService,如何在不停止执行程序的情况下停止动作?
【发布时间】:2013-07-02 07:02:14
【问题描述】:

我有这个代码:

ScheduledExecutorService scheduledExecutor;
.....
ScheduledFuture<?> result = scheduledExecutor.scheduleWithFixedDelay(
    new SomethingDoer(),0, measurmentPeriodMillis, TimeUnit.MILLISECONDS);

在某些事件之后我应该停止动作,这在 SomethingDoerrun() 方法中声明,它实现了 Runnable

我该怎么做?我无法关闭执行程序,我应该只撤销我的定期任务。我可以为此使用result.get() 吗?如果可以,请告诉我它是如何工作的。

【问题讨论】:

    标签: java executors


    【解决方案1】:

    使用result.cancel()ScheduledFuture 是您的任务的句柄。您需要取消此任务,该任务将不再执行。

    实际上,cancel(boolean mayInterruptIfRunning) 是签名,将其与true 参数一起使用将导致当前正在运行的执行线程被interrupt() 调用中断。如果线程在阻塞的可中断调用中等待,这将抛出一个中断的异常,例如Semaphore.acquire()。请记住,cancel 将仅确保该任务在停止执行后将不再执行。

    【讨论】:

      【解决方案2】:

      您可以使用ScheduledFuture 对象中的cancel() 方法。一旦取消,将不再执行任何任务。

      如果您希望停止当前正在运行的任务,您需要编写run 方法,使其对中断敏感,并将true 传递给cancel() 方法以请求中断。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多