gpt4 book ai didi

java - FutureTask 中的awaitDone 抛出InterruptedException

转载 作者:行者123 更新时间:2023-12-01 12:13:08 26 4
gpt4 key购买 nike

我已经在网上搜索了一个星期了,但没有像这样的帖子 How do I get FutureTask to return after TimeoutException?似乎回答了我的问题。我从我的代码中提取了一个代码示例:

 Future<Object> result = executorService.submit(new Callable<Object>() {
@Override public Object call() throws Exception {
...........
}
});

try {
return result.get(timeout.getValue(), timeout.getUnit().getTimeUnit());
} catch (TimeoutException e) {
result.cancel(true);
throw new TTimeoutException(e);
}

如果我运行这个,有时(千分之一)我会得到

 java.lang.InterruptedException
at java.util.concurrent.FutureTask.awaitDone(FutureTask.java:400)
at java.util.concurrent.FutureTask.get(FutureTask.java:199)
at com.abc.callers.A.call(A.java:83)

第 83 行是上面代码示例中显示的 future 任务的 result.get() 。

现在我的问题是,将来调用 result.cancel(true) 会导致 result.get 中出现 InterruptedException 吗?如果没有,谁可以改变我当前线程的中断状态? AFAIK result.get() 与运行我正在取消的提交任务的线程不是同一线程..

最佳答案

来自 Javadoc:

boolean cancel(boolean mayInterruptIfRunning)

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

After this method returns, subsequent calls to isDone() will always return true. Subsequent calls to isCancelled() will always return true if this method returned true.

因此,如果设置了 mayInterruptIfRunning,那么是的,它将尝试中断运行任务的线程。

换句话说,.cancel(true) 将尝试中断正在运行的任务,而 .cancel(false) 则不会。

听起来,如果您调用 .cancel(false) 并且任务尚未开始,result.get() 仍然会被中断。

关于java - FutureTask 中的awaitDone 抛出InterruptedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27171980/

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