如何在不停止执行程序的情况下停止操作

如何在不停止执行程序的情况下停止操作

本文介绍了ScheduledExecutorService,如何在不停止执行程序的情况下停止操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

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

在某些事件之后,我应该停止行动,声明在 run() SomethingDoer 的方法,它实现 Runnable

After some event I should stop action, which Declared in run() method of the SomethingDoer, which implements Runnable.

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

How can I do this? I can't shutdown executor, I should only revoke my periodic task. Can I use result.get() for this? And if I can, please tell me how it will work.

推荐答案

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

Use result.cancel(). The ScheduledFuture is the handle for your task. You need to cancel this task and it will not be executed any more.

实际上,取消(布尔值mayInterruptIfRunning)是签名并使用它与 true 参数将导致当前正在运行的exection的线程被 interrupt()中断呼叫。如果线程在阻塞可中断调用中等待,如 Semaphore.acquire(),这将抛出一个中断的异常。请记住, cancel 将确保只有在任务停止执行后不再执行该任务。

Actually, cancel(boolean mayInterruptIfRunning) is the signature and using it with true parameter will cause a currently running exection's thread to be interrupted with the interrupt() call. This will throw an interrupted exception if the thread is waiting in a blocking interruptible call, like Semaphore.acquire(). Keep in mind that cancel will ensure only that the task will not be executed any more once it stopped the execution.

这篇关于ScheduledExecutorService,如何在不停止执行程序的情况下停止操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:16