简体   繁体   English

如果在执行Future.get()时遇到InterruptedException,为什么还要执行Future.cancel()

[英]Why should I do Future.cancel() if I get InterruptedException when doing Future.get()

It is stated in Java Concurrency in Practice (Brian Goetz) (highlights are mine): 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抛出InterruptedExcetion或TimeoutException并且您知道程序不再需要结果时,请使用Future.cancel取消任务。

Javadoc for Future.get states that (highlight are mine): Javadoc for Future.get指出(重点是我的):

throws InterruptedException - if the current thread was interrupted while waiting 引发InterruptedException-如果当前线程在等待时中断

So, as far as I understand: if I get an InterruptedException then my task hasn't been started yet (because the executing thread was interrupted while waiting ). 因此,据我了解:如果收到InterruptedException,则我的任务尚未启动(因为正在等待的执行线程被中断了 )。 Then why do I have to cancel my task? 那为什么我必须取消我的任务?

Waiting in 等待中

throws InterruptedException - if the current thread was interrupted while waiting 引发InterruptedException-如果当前线程在等待时被中断

means that the current running thread (the one executing Future.get() ) was waiting for Future.get() to return. 表示当前正在运行的线程(执行Future.get()那个线程)正在等待Future.get()返回。 In general when a thread waits, it is like waiting to acquire an explicit lock , Object.wait() or for a blocking method in BlockingQueue . 通常,当线程等待时,就像等待获取显式锁 Object.wait()或在BlockingQueue获取阻塞方法一样。

Now about the quote from the book: if your current thread is interrupted (thus the InterruptedException ) and you interpret this as an abrupt cancellation, that you probably do not care anymore what the future will return, so should stop whatever the future does. 现在看书中的引文:如果您当前的线程被中断(因此InterruptedException ),并且您将此解释为突然取消,则您可能不再在乎将来会返回什么,因此应该停止将来所做的一切。

So you are wrong when you tell that the Thread hasn't been started. 因此,当您告诉线程尚未启动时,您就错了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM