gpt4 book ai didi

java - 通过 `Future` 检查 `get(0, TimeUnit.Microseconds)` 状态是个好主意吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:26:12 25 4
gpt4 key购买 nike

我有一个Future,我想知道它的状态。我想到的是这样的代码:

try {
// Is that a good idea? Counting on exceptions looks weird.
future.get(0, TimeUnit.MICROSECONDS);
this.status = DONE;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw Throwables.propagate(e);
} catch (ExecutionException e) {
this.status = FAILED;
} catch (TimeoutException e) {
this.status = RUNNING;
} catch (CancellationException e) {
this.status = CANCELED;
}

看起来 FutureTask 会尝试持有锁,如果它能拿到锁,就会检查 Future 的状态。所以这似乎是个好主意。

这里有我遗漏的陷阱吗?

最佳答案

作为suggested in the comments , 只需使用 Future.isDone检查运行状态。然而,您仍然需要调用 get() 来确定它是否成功完成,检查异常。

关于java - 通过 `Future` 检查 `get(0, TimeUnit.Microseconds)` 状态是个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14026513/

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