ScheduledExecutorService, how to stop action without stopping executor?

帅比萌擦擦* 提交于 2019-11-28 12:09:43

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.

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.

You can use the cancel() method from your ScheduledFuture object. 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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!