获取Executor提交的并发执行的任务返回结果的两种方式/ExecutorCompletionService使用
当我们通过Executor提交一组并发执行的任务,并且希望在每一个任务完成后能立即得到结果,有两种方式可以采取:
方式一:
通过一个list来保存一组future,然后在循环中轮训这组future,直到每个future都已完成。如果我们不希望出现因为排在前面的任务阻塞导致后面先完成的任务的结果没有及时获取的情况,那么在调用get方式时,需要将超时时间设置为0
- public class CompletionServiceTest {
- static class Task implements Callable<String>{
- private int i;
- public Task(int i){
- this.i = i;
- }
- @Override
- public String call() throws Exception {
- Thread.sleep(10000);
- return Thread.currentThread().getName() + "执行完任务:" + i;
- }
- }
- public static void main(String[] args){
- testUseFuture();
- }
- private static void testUseFuture(){
- int numThread = 5;
- ExecutorService executor = Executors.newFixedThreadPool(numThread);
- List<Future<String>> futureList = new ArrayList<Future<String>>();
- for(int i = 0;i<numThread;i++ ){
- Future<String> future = executor.submit(new CompletionServiceTest.Task(i));
- futureList.add(future);
- }
- while(numThread > 0){
- for(Future<String> future : futureList){
- String result = null;
- try {
- result = future.get(0, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- e.printStackTrace();
- } catch (TimeoutException e) {
- //超时异常直接忽略
- }
- if(null != result){
- futureList.remove(future);
- numThread--;
- System.out.println(result);
- //此处必须break,否则会抛出并发修改异常。(也可以通过将futureList声明为CopyOnWriteArrayList类型解决)
- break;
- }
- }
- }
- }
- }
方式二:
第一种方式显得比较繁琐,通过使用ExecutorCompletionService,则可以达到代码最简化的效果。
- public class CompletionServiceTest {
- static class Task implements Callable<String>{
- private int i;
- public Task(int i){
- this.i = i;
- }
- @Override
- public String call() throws Exception {
- Thread.sleep(10000);
- return Thread.currentThread().getName() + "执行完任务:" + i;
- }
- }
- public static void main(String[] args) throws InterruptedException, ExecutionException{
- testExecutorCompletionService();
- }
- private static void testExecutorCompletionService() throws InterruptedException, ExecutionException{
- int numThread = 5;
- ExecutorService executor = Executors.newFixedThreadPool(numThread);
- CompletionService<String> completionService = new ExecutorCompletionService<String>(executor);
- for(int i = 0;i<numThread;i++ ){
- completionService.submit(new CompletionServiceTest.Task(i));
- }
- }
- for(int i = 0;i<numThread;i++ ){
- System.out.println(completionService.take().get());
- }
- }
ExecutorCompletionService分析:
CompletionService是Executor和BlockingQueue的结合体。
- public ExecutorCompletionService(Executor executor) {
- if (executor == null)
- throw new NullPointerException();
- this.executor = executor;
- this.aes = (executor instanceof AbstractExecutorService) ?
- (AbstractExecutorService) executor : null;
- this.completionQueue = new LinkedBlockingQueue<Future<V>>();
- }
任务的提交和执行都是委托给Executor来完成。当提交某个任务时,该任务首先将被包装为一个QueueingFuture,
- public Future<V> submit(Callable<V> task) {
- if (task == null) throw new NullPointerException();
- RunnableFuture<V> f = newTaskFor(task);
- executor.execute(new QueueingFuture(f));
- return f;
- }
QueueingFuture是FutureTask的一个子类,通过改写该子类的done方法,可以实现当任务完成时,将结果放入到BlockingQueue中。
- private class QueueingFuture extends FutureTask<Void> {
- QueueingFuture(RunnableFuture<V> task) {
- super(task, null);
- this.task = task;
- }
- protected void done() { completionQueue.add(task); }
- private final Future<V> task;
- }
而通过使用BlockingQueue的take或poll方法,则可以得到结果。在BlockingQueue不存在元素时,这两个操作会阻塞,一旦有结果加入,则立即返回。
- public Future<V> take() throws InterruptedException {
- return completionQueue.take();
- }
- public Future<V> poll() {
- return completionQueue.poll();
- }
- 原文:http://xw-z1985.iteye.com/blog/1997077
获取Executor提交的并发执行的任务返回结果的两种方式/ExecutorCompletionService使用的更多相关文章
- Java并发编程:线程间协作的两种方式:wait、notify、notifyAll和Condition
Java并发编程:线程间协作的两种方式:wait.notify.notifyAll和Condition 在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者 ...
- 19、Java并发编程:线程间协作的两种方式:wait、notify、notifyAll和Condition
Java并发编程:线程间协作的两种方式:wait.notify.notifyAll和Condition 在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者 ...
- 并发编程 - 进程 - 1.开启子进程的两种方式/2.查看pid/3.Process对象的其他属性或方法/4.守护进程
1.开启子进程的两种方式: # 方式1: from multiprocessing import Process import time def task(name): print('%s is ru ...
- 并发编程 - 线程 - 1.开启线程的两种方式/2.进程与线程的区别/3.Thread对象的其他属性或方法/4.守护线程
1.开启线程的两种方式: 进程,线程: 进程只是用来把资源集中到一起(进程只是一个资源单位,或者说资源集合)而线程才是cpu上的执行单位) 1.同一个进程内的多个线程共享该进程内的地址资源 2.创建线 ...
- 获取表单选中的值(利用php和js两种方式)
php代码中获取表单中单选按钮的值: (单选按钮只能让我们选择一个,这里有一个“checked”属性,这是用来默认选取的,我们每次刷新我们的页面时就默认为这个值.) 例: <form name= ...
- JavaWeb学习总结(十五)Jsp中提交的表单的get和post的两种方式
两者的比较: Get方式: 将请求的参数名和值转换成字符串,并附加在原来的URL之后,不安全 传输的数据量较小,一般不能大于2KB: post方式: 数量较大: 请求的参数和值放在HTML的请求头中, ...
- 获取select文本框的下拉菜单文字内容的两种方式
<body> <div class="box"> <select id="sel"> <option value=&q ...
- 【linux】linux 下 shell命令 执行结果赋值给变量【两种方式】
方法1:[通用方法] 使用Tab键上面的反引号 例子如下: find命令 模糊查询在/apps/swapping目录下 查找 文件名中包含swapping并且以.jar结尾的文件 使用反引号 引住命令 ...
- python执行系统命令后获取返回值的几种方式集合
python执行系统命令后获取返回值的几种方式集合 今天小编就为大家分享一篇python执行系统命令后获取返回值的几种方式集合,具有很好的参考价值,希望对大家有所帮助.一起跟随小编过来看看吧 第一种情 ...
随机推荐
- python初识生成器 迭代器
生成器 带有 yield 的函数在 Python 中被称之为 generator(生成器) def xragns(): #定义函数生成器 print('小伙') yield ('好') #加上yiel ...
- 绘制图形与3D增强技巧(五)----多边形图元的使用及其他
1.注意多边形图元中的多边形只能是平面的,而且必须为凸多边形,且多边形的边不能弯曲 2.细分和边界,可以人为设置边界边和非边界边 glEdgeFlag(true)//接下来所有点均为边界边起点 glE ...
- BZOJ 1109: [POI2007]堆积木Klo
1109: [POI2007]堆积木Klo Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 948 Solved: 341[Submit][Statu ...
- Leetcode #2 Add two number
Q: You are given two linked lists representing two non-negative numbers. The digits are stored in re ...
- Leetcode # 169, 229 Majority Element I and II
Given an array of size n, find the majority element. The majority element is the element that appear ...
- http80端口转发(实现微信公众号接口绑定IP时,同时支持多个公众号)
http80端口转发 背景 微信公众平台接口绑定服务器时,如果使用IP需要使用80端口,此组件可实现一个IP上绑定多个公众平台接口 使用方法 http://(IP)/WeixinMP/(转发的地址Ba ...
- poj1113 凸包
result=对所有点凸包周长+pi*2*L WA了一次,被Pi的精度坑了 以后注意Pi尽可能搞精确一点.Pi=3.14还是不够用 Code: #include<vector> #incl ...
- C#关闭窗口代码
if (MessageBox.Show("请您确认是否退出(Y/N)", "系统提示", MessageBoxButtons.YesNo, MessageBox ...
- Newton-Raphson算法简介及其R实现
本文简要介绍了Newton-Raphson方法及其R语言实现并给出几道练习题供参考使用. 下载PDF格式文档(Academia.edu) Newton-Raphson Method Let $f(x) ...
- 用DOS命令打开IE浏览器、我的文档等等
用DOS命令打开IE浏览器 在“start”-运行中直接输入网址就可以了.如输入百度: http://www.baidu.com Command:[ start http://www.baidu.c ...