java ScheduledExecutorService,如何在不停止执行器的情况下停止动作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17419386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:57:24  来源:igfitidea点击:

ScheduledExecutorService, how to stop action without stopping executor?

javaexecutors

提问by user2541398

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.

在某些事件之后,我应该停止在 的run()方法中声明的操作,该方法SomethingDoer实现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? And if I can, please tell me how it will work.

我怎样才能做到这一点?我不能关闭执行程序,我应该只撤销我的定期任务。我可以用result.get()这个吗?如果可以,请告诉我它将如何运作。

回答by allprog

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

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

Actually, cancel(boolean mayInterruptIfRunning)is the signature and using it with trueparameter 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 cancelwill ensure only that the task will not be executed any more once it stopped the execution.

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

回答by Duncan Jones

You can use the cancel()method from your ScheduledFutureobject. Once cancelled, no further tasks will be executed.

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

If you want your currently running task to stop, you need to code your runmethod so it is sensitive to interrupts and pass trueto the cancel()method to request an interrupt.

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