问题
I've implemented subscription in my Java app. When new subscriber added, the application creates new task (class which implements Runnable
to be run in the separate thread) and it is added to the ExecutorService
like:
public void Subscribe()
{
es_.execute(new Subscriber(this, queueName, handler));
}
//...
private ExecutorService es_;
Application may register as many subscribers as you want. Now I want implement something like Unsubscribe
so every subscriber has an ability to stop the message flow. Here I need a way to stop one of the tasks running in the ExecutorService
. But I don't know how I can do this.
The ExecutorService.shutdown()
and its variations are not for me: they terminates all the tasks, I want just terminate one of them. I'm searching for a solution. As simple as possible. Thanks.
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/13929618/stop-a-runnable-submitted-to-executorservice