我们如何在Java中使用回调方法来加入并行处理的多个线程的结果?

最佳答案

您可以使用CompletionService。当它们从执行程序线程变为可用时,它将在队列中接收Future结果。从技术上讲,它不是回调,但是像回调一样。例如:

public class Main {

    public static void main(String... args) {
        CompletionService<SomeResult> completionService =
           new ExecutorCompletionService<SomeResult>(executor);

        ResultProcessor processor = new ResultProcessor(completionService);
        processor.start();

        completionService.submit(new Callable<SomeResult>() {
           public SomeResult call() {
               ...
               return result;
           }
        });
    }
}

class SomeResult {}

class ResultProcessor extends Thread {
   private CompletionService<SomeResult> completionService;

   ResultProcessor(CompletionService completionService) {
       this.completionService = completionService;
   }

   public void run() {
      while(...) {
          Future<SomeResult> resultFuture = completionService.take(); //blocks if none available
          SomeResult result = resultFuture.get();
          ... // result processing
      }
   }
}

07-28 13:20