停止提交给ExecutorService的Runnable [英] Stop a Runnable submitted to ExecutorService

查看:177
本文介绍了停止提交给ExecutorService的Runnable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Java应用程序中实现了订阅.添加新的订户后,应用程序将创建新任务(实现Runnable的类以在单独的线程中运行)并将其添加到ExecutorService中,例如:

public void Subscribe()
{
    es_.execute(new Subscriber(this, queueName, handler));
}

//...

private ExecutorService es_;

应用程序可以根据需要注册任意数量的订阅者.现在,我想要实现类似Unsubscribe的功能,以便每个订阅者都可以停止消息流.在这里,我需要一种方法来停止在ExecutorService中运行的任务之一.但是我不知道该怎么办.

ExecutorService.shutdown()及其变体不适合我:它们终止所有任务,我只想终止其中一项任务.我正在寻找解决方案.尽可能简单.谢谢.

解决方案

您可以使用未来#cancel

示例(假设SubscriberRunnable):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆