JDK5 如何获取所有线程池的结果再继续执行

来源:互联网 发布:淘宝上兰可欣那么便宜 编辑:程序博客网 时间:2024/06/06 01:28


JDK5的Callable和Future组合使用可以获取单个线程的执行的结果。那如何获取多个线程的执行结果呢?

别急,CompletionService的存在,让这一切变的那么简单。

首先CompletionService需要一个Executor线程池为参数构造一个新对象,如

 

ExecutorService objExecutorService = Executors.newFixedThreadPool(3);
CompletionService<String> objCompletionService = new ExecutorCompletionService<String>(objExecutorService);

泛型既返回的参数类型。

然后使用CompletionService.submit(Callable)接受需要执行的任务。

如:

for(int i= 0;i<10;i++){final int iResult = i;objCompletionService.submit(new Callable<String>() {public String call() throws Exception {Thread.sleep(new Random().nextInt(10*1000));return "第"+iResult+"线程执行返回结果";}});}

最后使用CompletionService.take().get()获取结果,如


for (int i = 0; i < 10; i++) {try {System.out.println(objCompletionService.take().get());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}}

 

ok!

 

完整代码为:

 ExecutorService objExecutorService = Executors.newFixedThreadPool(3);
  CompletionService<String> objCompletionService = new ExecutorCompletionService<String>(
    objExecutorService);

  for(int i= 0;i<10;i++){
   
   final int iResult = i;
   objCompletionService.submit(new Callable<String>() {
    
    public String call() throws Exception {
     Thread.sleep(new Random().nextInt(10*1000));
     return "第"+iResult+"线程执行返回结果";
    }
    
   });
  }
  
  for (int i = 0; i < 10; i++) {
   try {
    System.out.println(objCompletionService.take().get());
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (ExecutionException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  System.out.println("继续往下执行");

 

执行结果为:

 

从执行结果可以看出,会产生阻塞等待所有线程执行完成再继续。


 

原创粉丝点击