停止提交给ExecutorService的Runnable [英] Stop a Runnable submitted to ExecutorService
问题描述
我已经在Java应用程序中实现了订阅.添加新的订户后,应用程序将创建新任务(实现Runnable
的类以在单独的线程中运行)并将其添加到ExecutorService
中,例如:
public void Subscribe()
{
es_.execute(new Subscriber(this, queueName, handler));
}
//...
private ExecutorService es_;
应用程序可以根据需要注册任意数量的订阅者.现在,我想要实现类似Unsubscribe
的功能,以便每个订阅者都可以停止消息流.在这里,我需要一种方法来停止在ExecutorService
中运行的任务之一.但是我不知道该怎么办.
ExecutorService.shutdown()
及其变体不适合我:它们终止所有任务,我只想终止其中一项任务.我正在寻找解决方案.尽可能简单.谢谢.
您可以使用未来#cancel >
示例(假设Subscriber
是Runnable
):
Future<?> future = es_.submit(new Subscriber(this, queueName, handler));
...
future.cancel(true); // true to interrupt if running
评论中的重要提示:
If your task doesn't honour interrupts and it has already started, it will run to completion.
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.
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.
这篇关于停止提交给ExecutorService的Runnable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!