简体   繁体   English

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

[英]ScheduledExecutorService, how to stop action without stopping executor?

I have this code: 我有以下代码:

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

After some event I should stop action, which Declared in run() method of the SomethingDoer , which implements Runnable . 在发生一些事件之后,我应该停止操作,该操作在SomethingDoer run()方法中声明,该方法实现了Runnable

How can I do this? 我怎样才能做到这一点? I can't shutdown executor, I should only revoke my periodic task. 我无法关闭执行器,只能撤消我的定期任务。 Can I use result.get() for this? 我可以result.get()使用result.get()吗? And if I can, please tell me how it will work. 如果可以的话,请告诉我它如何工作。

Use result.cancel() . 使用result.cancel() The ScheduledFuture is the handle for your task. ScheduledFuture是您的任务的句柄。 You need to cancel this task and it will not be executed any more. 您需要取消此任务,它将不再执行。

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. 实际上, cancel(boolean mayInterruptIfRunning)是签名,将其与true参数一起使用将导致当前正在运行的执行线程被interrupt()调用interrupt() This will throw an interrupted exception if the thread is waiting in a blocking interruptible call, like Semaphore.acquire() . 如果线程正在等待阻塞的可中断调用(例如Semaphore.acquire() ,则将抛出一个中断的异常。 Keep in mind that cancel will ensure only that the task will not be executed any more once it stopped the execution. 请记住, cancel将确保仅在任务停止执行后不再执行该任务。

You can use the cancel() method from your ScheduledFuture object. 您可以从ScheduledFuture对象使用cancel()方法。 Once cancelled, no further tasks will be executed. 一旦取消,将不再执行其他任务。

If you want your currently running task to stop, you need to code your run method so it is sensitive to interrupts and pass true to the cancel() method to request an interrupt. 如果要停止当前正在运行的任务,则需要对run方法进行编码,以使其对中断敏感并将true传递给cancel()方法以请求中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM