我在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);
现在假设我故意在上面的第二个调用中创建一个异常,并在一个try / catch块中包含所有3个调用get()我没有看到异常来捕获块而我的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块中,我就可以捕获它们。为什么?此外,当我开始在try catch块中包含每个get()方法时,我失去了多线程。方法调用逐个进行编码
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
}
当我能够捕获异常时,我失去了多线程,当我能够生成多线程时,我失去了异常。
任何想法如何单独处理异常并同时实现多线程
答案 0 :(得分: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
答案 1 :(得分:0)
ExecutorCompletionService应该有助于解决您的问题。您的代码需要实现队列机制来处理结果,ExecutorCompletionService应该有所帮助。看看吧。