Java 等待未来的清单
我有一种返回List期货的方法
List<Future<O>> futures = getFutures();现在,我要等待,直到所有期货都成功完成处理,或者所有由期货返回输出的任务都引发异常。即使一项任务引发异常,也没有必要等待其他期货。
简单的方法是
wait() {   For(Future f : futures) {
     try {
       f.get();
     } catch(Exception e) {
       //TODO catch specific exception
       // this future threw exception , means somone could not do its task
       return;
     }
   }
}
但是这里的问题是,例如,如果第4个期货抛出异常,那么我将不必要地等待前3个期货可用。
如何解决呢?会以任何方式倒计时闩锁帮助吗?我无法使用Future,isDone因为Java文档说
boolean isDone()Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.
回答:
你可以使用CompletionService在期货准备就绪时立即接收它们,如果其中之一引发异常,则取消处理。像这样:
Executor executor = Executors.newFixedThreadPool(4);CompletionService<SomeResult> completionService = 
       new ExecutorCompletionService<SomeResult>(executor);
//4 tasks
for(int i = 0; i < 4; i++) {
   completionService.submit(new Callable<SomeResult>() {
       public SomeResult call() {
           ...
           return result;
       }
   });
}
int received = 0;
boolean errors = false;
while(received < 4 && !errors) {
      Future<SomeResult> resultFuture = completionService.take(); //blocks if none available
      try {
         SomeResult result = resultFuture.get();
         received ++;
         ... // do something with the result
      }
      catch(Exception e) {
             //log
         errors = true;
      }
}
我认为,如果其中一个抛出错误,你可以进一步取消任何仍在执行的任务。
以上是 Java 等待未来的清单 的全部内容, 来源链接: utcz.com/qa/401661.html
