Stop a Runnable submitted to ExecutorService

北城以北 提交于 2019-12-04 03:12:08

You can use ExecutorService#submit instead of execute and use the returned Future object to try and cancel the task using Future#cancel

Example (Assuming Subscriber is a Runnable):

Future<?> future = es_.submit(new Subscriber(this, queueName, handler));
...
future.cancel(true); // true to interrupt if running

Important note from the comments:

If your task doesn't honour interrupts and it has already started, it will run to completion.

Instead of using ExecutorService.execute(Runnable) try using Future<?> submit(Runnable). This method will submit the Runnable into the pool for execution and it will return a Future object. By doing this you will have references to all subscriber threads.

In order to stop particular thread just use futureObj.cancel(true). This will interrupt the running thread, throwing an InterruptedException. The subscriber thread should be coded such way it will stop processing in the case of this exception (for example Thread.sleep(millis) with wrapper try / catch block for the whole method).

You cand find more information on the official API: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

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