0

我在我的 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
    }

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

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

4

2 回答 2

2

我真的不喜欢这个。正确的答案是使用 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

于 2011-07-15T01:53:56.623 回答
0

ExecutorCompletionService 应该有助于解决您的问题。您的代码需要实现一个队列机制来处理结果,并且 ExecutorCompletionService 应该会有所帮助。看看这个。

于 2011-07-15T01:53:26.360 回答