java - 并发 - 中断 Future 而不取消它

标签 java multithreading concurrency future interrupted-exception

有什么方法可以在不取消 Future 的情况下中断它吗?

java doc API:

boolean cancel (boolean mayInterruptIfRunning)

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

要捕获中断,我们必须正确捕获中断异常或检查 Runnable/Callable 方法中的 isInterrupted() 方法。

但是没有办法使用 Future 接口(interface)来中断正在运行的 Future

由于所有线程都在Executor Service池中,所以没有人可以做thread.interrupt()。 这就是为什么假设只有当 Future 被取消或线程池终止时才会出现任何中断吗?

我试图理解为什么 Future 接口(interface)中没有中断方法。 任何帮助将不胜感激

最佳答案

原因是因为Future的抽象和线程中具体执行的区别。我们不能说 future 是绑定(bind)到单线程还是多线程。 Future 可能会启动新的线程,启动新的 futures 等。

将这些抽象视为客户端代码和 future 执行者之间的交互。从概念上讲,说“取消我要求你做的这个任务”是有意义的,因为取消是你的任务。我可能正在忙于它,或者我可能还没有开始它,或者它可能已经完成但没关系,如果你想让我取消它。这就是为什么我们有一个取消方法。

另一方面,说“打断你的任务”并没有多大意义。由于操作结果(Future)和执行模型(比如 Executor)之间的解耦,客户端不知道正在采取什么操作来完成任务。那么如何才能期望客户端知道何时中断是适当的、需要的,甚至是支持的。

关于java - 并发 - 中断 Future 而不取消它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8901739/

相关文章:

c++ - concurrent_vector 无效数据

java - Mac Mavericks Java 无法找到可执行文件 bash_profile 编辑不起作用

c# - 多线程求和给出不正确的结果

c# - 如何在新线程上运行任务并立即返回给调用者?

java - Servlet 似乎同步处理多个并发浏览器请求

multithreading - std::condition_variable::wait 访问冲突

java - 在 Lucene 中索引多个用户的数据的最佳实践是什么

java - 如何将数组列表的元素添加到一起

java - 从 DBpedia 资源中获取 Sesame 2.7.1 的数据类型错误

java - 多线程环境下初始化前读取非final字段的代码演示