gpt4 book ai didi

java - Future.get() 在什么情况下会抛出 ExecutionException 或 InterruptedException

转载 作者:IT老高 更新时间:2023-10-28 20:38:58 26 4
gpt4 key购买 nike

我的代码片段:

ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Task t = new Task(response,inputToPass,pTypes,unit.getInstance(),methodName,unit.getUnitKey());
Future<SCCallOutResponse> fut = executor.submit(t);
response = fut.get(unit.getTimeOut(),TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
// if the task is still running, a TimeOutException will occur while fut.get()
cat.error("Unit " + unit.getUnitKey() + " Timed Out");
response.setVote(SCCallOutConsts.TIMEOUT);
} catch (InterruptedException e) {
cat.error(e);
} catch (ExecutionException e) {
cat.error(e);
} finally {
executor.shutdown();
}

我应该如何处理代码中的InterruptedExceptionExecutionException

在什么情况下会抛出这些异常?

最佳答案

ExecutionExceptionInterruptedException 是两个截然不同的东西。

ExecutionException 包装了正在执行的线程抛出的任何异常,因此,例如,如果您的线程正在执行某种导致 IOException 被抛出的 IO,那么会被包裹在 ExecutionException 中并重新抛出。

InterruptedException 并不表示出现任何问题。它可以为您提供一种方法,让您的线程知道何时该停止,以便它们可以完成当前工作并优雅地退出。假设我希望我的应用程序停止运行,但我不希望我的线程在某些事情中间放弃他们正在做的事情(如果我让它们成为守护线程会发生这种情况)。所以当应用程序关闭时,我的代码在这些线程上调用中断方法,在它们上设置中断标志,下次这些线程等待或 hibernate 时,它们会检查中断标志并抛出 InterruptedException,我可以用它来摆脱线程参与的任何无限循环处理/ sleep 逻辑。(如果线程不等待或 sleep ,它可以定期检查中断标志。)所以它是用于更改逻辑流的异常实例。您完全记录它的唯一原因是在示例程序中向您展示正在发生的事情,或者如果您正在调试中断逻辑无法正常工作的问题。

关于java - Future.get() 在什么情况下会抛出 ExecutionException 或 InterruptedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2665569/

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