gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:01:24 25 4
gpt4 key购买 nike

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 做什么,都应该停止。

所以当您告诉 Thread 尚未启动时,您错了。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com