我有这个代码:
ScheduledExecutorService scheduledExecutor;
.....
ScheduledFuture<?> result = scheduledExecutor.scheduleWithFixedDelay(
new SomethingDoer(),0, measurmentPeriodMillis, TimeUnit.MILLISECONDS);
Run Code Online (Sandbox Code Playgroud)
某些事件后,我应该停止行动,这在申报run()的方法SomethingDoer,它实现Runnable.
我怎样才能做到这一点?我无法关闭执行程序,我应该只撤销我的周期性任务.我可以用result.get()它吗?如果可以,请告诉我它将如何运作.
all*_*rog 14
使用result.cancel().这ScheduledFuture是你的任务的句柄.您需要取消此任务,它将不再执行.
实际上,cancel(boolean mayInterruptIfRunning)签名和使用它与true参数将导致当前正在运行的exection的线程被interrupt()调用中断.如果线程在阻塞可中断调用中等待,这将抛出一个中断的异常,如Semaphore.acquire().请记住,cancel只有在任务停止执行后才会确保任务不再执行.
您可以cancel()从ScheduledFuture对象中使用该方法。一旦取消,将不再执行其他任务。
如果要停止当前正在运行的任务,则需要对run方法进行编码,以使其对中断敏感,然后传递true给该cancel()方法以请求中断。