Jdk8优化总结(一)ExecutorCompletionService
1.ExecutorCompletionService高并发编程
问题描述:我们在使用线程池时是通过向线程池中不断submit异步的任务,同时需要保存每个任务相关的Future,
最后遍历Future,虽然执行任务的速度是大大改善了,但是我们的任务执行完成之后遍历Future的过程是堵塞的,
只要有一个任务没有执行完成,那么所有的任务都需要等待。
解决思路: 如果我们然哪个任务执行完成后就能拿到Future中的结果,那效率是不是更高了呢
ExecutorCompletionService就帮助我们实现了这样一个效果,它的内部是一个先进先出的队列,通过调用它的
take或者poll方法拿到执行完成的Future,进而通过调用Future中的get方法拿到最终的结果。
不多说了,上代码。
static ExecutorService executorService = Executors.newFixedThreadPool(100);
ExecutorCompletionService<Integer> completionService = new
ExecutorCompletionService<>(executorService);
completionService.submit(new CalculateArticleScoreA());
completionService.submit(new CalculateArticleScoreB());
completionService.submit(new CalculateArticleScoreC());
public static void main(String[] args) {
ExecutorCompletionService<Integer> completionService = new ExecutorCompletionService<>(executorService);
completionService.submit(new CalculateArticleScoreA());
completionService.submit(new CalculateArticleScoreB());
completionService.submit(new CalculateArticleScoreC());
doSomeThings();
Integer result = 0;
for (int i = 0; i < 3; i++) {
try {
Integer integer = completionService.take().get();
result+=integer;
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
System.out.println(result);
executorService.shutdown();
}
private static class CalculateArticleScoreB implements java.util.concurrent.Callable<Integer> {
@Override
public Integer call() throws Exception {
Random random = new Random();
TimeUnit.SECONDS.sleep(30);
System.out.println(Thread.currentThread().getName());
return random.nextInt(100);
}
}
private static class CalculateArticleScoreC implements java.util.concurrent.Callable<Integer> {
@Override
public Integer call() throws Exception {
Random random = new Random();
TimeUnit.SECONDS.sleep(20);
System.out.println(Thread.currentThread().getName());
return random.nextInt(100);
}
}