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/