jdk8的CompletionService
本质是一个阻塞队列,能够让先完成的任务先返回Future。当然,这有以下必要因素:
1.执行器的线程个数要充足,能够立即执行任务,而执行器的队列里面不存在等待执行的任务。
2.只能调用poll和take方法,才能先返回先执行完成的任务
submit方法跟普通的执行器的方法原理类似。
这个类是一次一消费类,执行完就可以放弃了。
内部原理,定义一个内部类,这个内部类覆盖done方法,当完成时,就把Future放到外部类的阻塞队列里面即可。
本质其实就是一个阻塞队列而已。
public class Task implements Callable<Integer>{
private Integer no;
public Task(Integer no) {
this.no = no;
}
@Override
public Integer call() {
try {
TimeUnit.SECONDS.sleep((long)no.intValue());
} catch (InterruptedException e) {
e.printStackTrace();
}
return this.no;
}
}
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,2,60, TimeUnit.SECONDS,new ArrayBlockingQueue<>(100));
CompletionService completionService = new ExecutorCompletionService(threadPoolExecutor);
try{
completionService.submit(new Task(Integer.parseInt("4")));
completionService.submit(new Task(Integer.parseInt("1")));
for(int i=0;i<2;i++){
Future<Integer> f = completionService.take();
System.out.println(f.get());
}
threadPoolExecutor.shutdown();
}catch (Exception e){
e.printStackTrace();
}
}