java - 如果在执行 Future.get() 时出现 InterruptedException,为什么我应该执行 Future.cancel()

标签 java multithreading concurrency

Java 并发实践 (Brian Goetz) 中有说明(重点内容是我的):

When Future.get throws InterruptedExcetion or TimeoutException and you know that the result is no longer needed by the program, cancel the task with Future.cancel

Future.get 的 Javadoc 指出(重点是我的):

throws InterruptedException - if the current thread was interrupted while waiting

因此,据我了解:如果我收到 InterruptedException,则我的任务尚未开始(因为执行线程在等待时被中断)。那我为什么要取消任务呢?

最佳答案

等待

throws InterruptedException - if the current thread was interrupted while waiting

表示当前正在运行的线程(执行 Future.get() 的线程)正在等待 Future.get() 返回。一般来说,当线程等待时,就像等待获取 explicit lock , Object.wait()或者用于 BlockingQueue 中的阻塞方法。

现在引用书中的一句话:如果您当前的线程被中断(因此出现 InterruptedException)并且您将其解释为突然取消,那么您可能不再关心 future 将返回什么,所以无论 future 做什么都应该停止。

所以当你说线程尚未启动时你错了。

关于java - 如果在执行 Future.get() 时出现 InterruptedException,为什么我应该执行 Future.cancel(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31986915/

相关文章:

python - 使用 Twisted 的简单非网络并发

java - 递归题: Revision

java - java.lang.UnsupportedClassVersionError不支持的major.minor版本51.0 rhdfs

JavaFX 8 : Separation of model/domain from view

java - Java中的计数器循环

.net - .NET中的绿色线程

java - 重构多线程异步应用程序以防止线程过多

Java lambda LinkedBlockingQueue 意外行为

java - 可重入锁在 Java 中工作正常,但在 Scala 中导致 IllegalMonitorException

java - java for 循环中的并发