一、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