gpt4 book ai didi

java - 发生异常时 future 任务异步调用挂起

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

我在我的java程序中写了很多异步 future 任务调用。下面给出一个示例

FutureTask<List<ConditionFact>> x = getConditionFacts(final Member member);
FutureTask<List<RiskFact>> x = getRiskFacts(final Member member);
FutureTask<List<SAEFact>> x = getSAEFacts(final Member member);

现在假设我故意在上面的第二个调用中创建一个异常,并将所有 3 个调用 get() 包含在一个 try/catch block 中,我没有看到异常进入 catch block ,并且我的 java 程序只是静止不动。所有 3 个方法调用都是同时发生的。

try {   
FutureTask<List<ConditionFact>> task = getConditionFacts(member);
// wait for the task to complete and get the result:

List<ConditionFact> conditionFacts = task.get();

FutureTask<List<ConditionFact>> task = getRiskFacts(member);
// wait for the task to complete and get the result:

List<RiskFact> conditionFacts = task.get();
}
catch (ExecutionException e) {
// an exception occurred.
Throwable cause = e.getCause(); // cause is the original exception thrown by the DAO
}

但是如果我将每个 get() 包含在单独的 try catch block 中,我就能够捕获它们。为什么?另外,当我开始将每个 get() 方法包含在 try catch block 中时,我就失去了多线程。方法调用按照编码一一发生

      FutureTask<List<ConditionFact>> task = getConditionFacts(member);
// wait for the task to complete and get the result:
try {
List<ConditionFact> conditionFacts = task.get();
}
catch (ExecutionException e) {
// an exception occurred.
Throwable cause = e.getCause(); // cause is the original exception thrown by the DAO
}
FutureTask<List<ConditionFact>> task = getRiskFacts(member);
// wait for the task to complete and get the result:
try {
List<RiskFact> conditionFacts = task.get();
}
catch (ExecutionException e) {
// an exception occurred.
Throwable cause = e.getCause(); // cause is the original exception thrown by the DAO
}

当我能够捕获异常时,我会丢失多线程,而当我能够生成多线程时,我会丢失异常。

如何单独处理异常并同时实现多线程

最佳答案

我真的很不喜欢这个。正确的答案是使用 ExecutorService 来运行线程池中的任务。

ExecutorService executor = Executor.newFixedThreadPool(2);
FutureTask<List<ConditionFact>> task1 = getConditionFacts(member);
FutureTask<List<ConditionFact>> task2 = getRiskFacts(member);
executor.execute(task1);
executor.execute(task2);
// wait for the task to complete and get the result:
try {
List<ConditionFact> conditionFacts = task1.get();
}
catch (ExecutionException e) {
// an exception occurred.
Throwable cause = e.getCause(); // cause is the original exception thrown by the DAO
}
// wait for the task to complete and get the result:
try {
List<RiskFact> conditionFacts = task2.get();
}
catch (ExecutionException e) {
// an exception occurred.
Throwable cause = e.getCause(); // cause is the original exception thrown by the DAO
}

这将解决单线程执行问题。我在这里得到了答案:http://programmingexamples.wikidot.com/futuretask

关于java - 发生异常时 future 任务异步调用挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6701679/

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