您可以使用CompletableFuture为您的使用情况
static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
返回完成时任 给出CompletableFutures的完整的新CompletableFuture,与同结果。否则,如果 它异常完成,则返回的CompletableFuture也会执行 ,因此,带有此异常的CompletionException将作为其原因。 如果没有提供CompletableFutures,则返回一个不完整的 CompletableFuture。
您应该将所有期货存储在列表中。 `
现在
List<CompletableFuture<?>> futureList = // all futures;
while(futureList.size()>0){
CompletableFuture<?> completed = CompletableFuture.anyOf(futureList); //convert futureList to array
if(completed.isCompletedExceptionally()){
// first future that completed with an exception
}else{
//future completed without exception, store the result or process
futureList.remove(completed); // remove it from the incomplete list
}
}
您可能获得CompletableFuture
像
final CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
//...long running...
return "returnVal";
},
executor); //here executor is your executor pool
如果你不想使用明确的执行池
final CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
//...long running...
return "returnVal";
});
然而,在这种情况下,将提交至ForkJoinPool.commonmonitor()
为什么不包裹你的可调用函数并在包装器中处理每个错误? –