我在我的 java 程序中编写了许多异步未来任务调用。下面给出一个样本
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 块中,我没有看到异常进入 catch 块,我的 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 块中,我就可以捕获它们。为什么?此外,当我开始将每个 get() 方法包含在 try catch 块中时,我失去了多线程。方法调用按照编码一一发生
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
}
当我能够捕获异常时,我会丢失多线程,当我能够生成多线程时,我会丢失异常。
任何想法如何单独处理异常并同时实现多线程