java并发 CompletionService (八)

一、CompletionService的实现类:ExecutorCompletionService

       相当于ExecutorService与BlockingQueue的组合,即能够将一组任务的运行结果按结果的先后顺序放入阻

       塞队列中,以便逐一取出

 

二、适用场景:

      假定有针对某个问题的一组求解程序,每个求解程序都能返回某种类型的 Result 值,并且您想同时运行

      它们,使用方法 use(Result r) 处理返回非 null 值的每个求解程序的返回结果

 

三、代码示例:

 

    

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CompletionServiceTest {

	public static void main(String[] args) throws Exception{
		
		 //声明任务执行容器
		 ExecutorService executor=Executors.newCachedThreadPool();
		 CompletionService<String> ec=new ExecutorCompletionService<String>(executor) ;
		 
		 //初始化任务集合
		 List<CompletionServiceCallable> cs=new ArrayList<CompletionServiceCallable>();
		 cs.add(new CompletionServiceCallable());
		 cs.add(new CompletionServiceCallable());
		 cs.add(new CompletionServiceCallable());
		 cs.add(new CompletionServiceCallable());
		 cs.add(new CompletionServiceCallable());
		 cs.add(new CompletionServiceCallable());
		 
		 //提交任务
		 for(CompletionServiceCallable c :cs){
			 ec.submit(c);
		 }
		 
		 //获取任务执行的结果
		 int n=cs.size();
		 for(int i=0;i<n;i++){
			Future<String> r= ec.take(); 
			System.out.println("result:"+r.get());
		 }

		 //关闭线程池
		 executor.shutdown();
	}
	
}

 

 

     

import java.util.Random;
import java.util.concurrent.Callable;

public class CompletionServiceCallable implements Callable<String> {

	@Override
	public String call() throws Exception {
		//获取随机数
		Random rand = new Random();
		int rnd=rand.nextInt(99)+1;
		
		Thread.sleep(rnd*10);
		return "completed:"+rnd;
	}

}

 

 

四、运行结果

      result:completed:7

      result:completed:36

      result:completed:74

      result:completed:78

      result:completed:83

      result:completed:99

    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值