ScheduledExecutiorService,如何在不停止执行器的情况下停止操作



我有这个代码:

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

在某个事件之后,我应该停止操作,该操作在实现RunnableSomethingDoerrun()方法中声明。

我该怎么做?我不能关闭executor,我只能撤销我的定期任务。我可以使用result.get()吗?如果可以的话,请告诉我它将如何工作。

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

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

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

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

最新更新