接口CompletionService的功能是以异步的方式一边生产新的任务,一边处理已完成任务的结果,这样可以将执行任务与处理任务分离。使用submit()执行任务,使用take取得已完成的任务,并按照这些任务的时间顺序处理他们的结果。

使用CompletionService解决Future的缺点
public class MyCallable implements Callable<String> {
private String username;
private long sleepValue; public MyCallable(String username, long sleepValue) {
super();
this.username = username;
this.sleepValue = sleepValue;
} @Override
public String call() throws Exception {
System.out.println(username + " " + Thread.currentThread().getName() + System.currentTimeMillis());
Thread.sleep(sleepValue);
return "return " + username;
} public static void main(String[] args) {
try {
MyCallable callable1 = new MyCallable("username1", 5000);
MyCallable callable2 = new MyCallable("username2", 4000);
MyCallable callable3 = new MyCallable("username3", 3000);
MyCallable callable4 = new MyCallable("username4", 2000);
MyCallable callable5 = new MyCallable("username5", 1000); List<Callable<String>> callables = new ArrayList<>();
callables.add(callable1);
callables.add(callable2);
callables.add(callable3);
callables.add(callable4);
callables.add(callable5); int corePoolSize = 5;
int maximumPoolSize = 10;
int keepAliveTime = 5;
TimeUnit unit = TimeUnit.SECONDS;
LinkedBlockingDeque<Runnable> workQueue = new LinkedBlockingDeque<>();
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
CompletionService completionService = new ExecutorCompletionService<>(executor);
for (int i = 0; i < 5; i++) {
completionService.submit(callables.get(i));
}
for (int i = 0; i < 5; i++) {
//take方法:获取并移除表示下一个已完成任务的Future,如果目前不存在这样的任务,则等待。
System.out.println(completionService.take().get() + " -- " + System.currentTimeMillis());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

控制台打印结果如下:

username2  pool-1-thread-21470920687933
username4 pool-1-thread-41470920687934
username3 pool-1-thread-31470920687933
username5 pool-1-thread-51470920687934
username1 pool-1-thread-11470920687933
return username5 -- 1470920688939
return username4 -- 1470920689937
return username3 -- 1470920690938
return username2 -- 1470920691938
return username1 -- 1470920692938

从打印结果来看,CompletionService解决了Future阻塞的缺点,哪个任务先执行完,哪个任务就先返回值。在CompletionService接口中如果当前没有任务执行完,则completionService.take().get()方法还是呈阻塞特性。


take()方法
public class Run {
public static void main(String[] args) {
try {
ExecutorService executorService = Executors.newCachedThreadPool();
CompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);
for (int i = 0; i < 10; i++) {
completionService.submit(new Callable<String>() { @Override
public String call() throws Exception {
long sleepValue = (int)(Math.random() * 1000);
System.out.println("sleep=" + sleepValue + " " + Thread.currentThread().getName());
Thread.sleep(sleepValue);
return sleepValue + "-" + Thread.currentThread().getName();
}
});
}
for (int i = 0; i < 10; i++) {
//take()方法是按照任务执行的速度,从快到慢获得Future对象
System.out.println(completionService.take().get());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

打印结果如下:

sleep=662 pool-1-thread-2
sleep=476 pool-1-thread-6
sleep=977 pool-1-thread-5
sleep=175 pool-1-thread-7
sleep=461 pool-1-thread-4
sleep=836 pool-1-thread-3
sleep=267 pool-1-thread-1
sleep=82 pool-1-thread-8
sleep=714 pool-1-thread-9
sleep=946 pool-1-thread-10
82-pool-1-thread-8
175-pool-1-thread-7
267-pool-1-thread-1
461-pool-1-thread-4
476-pool-1-thread-6
662-pool-1-thread-2
714-pool-1-thread-9
836-pool-1-thread-3
946-pool-1-thread-10
977-pool-1-thread-5

take()方法是按照任务执行的速度,从快到慢获得Future对象


poll()方法
public class Run1 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
CompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);
completionService.submit(new Callable<String>() { @Override
public String call() throws Exception {
TimeUnit.SECONDS.sleep(3);
System.out.println("3秒过了");
return "3S";
}
});
//poll()方法获取并移除表示下一个已完成任务的Future,
//如果不存在这样的任务则返回null,无阻塞效果
System.out.println(completionService.poll());
}
}

打印结果如下:

null
3秒过了

方法poll()返回的Future为null,因为当前没有任何已完成任务的Future对象。poll()不像take()方法具有阻塞的效果。


类CompletionService与异常
public class MyCalableA implements Callable<String> {

	@Override
public String call() throws Exception {
System.out.println("MyCalableA begin," + System.currentTimeMillis());
TimeUnit.SECONDS.sleep(1);
System.out.println("MyCalableA end," + System.currentTimeMillis());
return "MyCalableA";
} } public class MyCalableB implements Callable<String> { @Override
public String call() throws Exception {
System.out.println("MyCalableB begin," + System.currentTimeMillis());
TimeUnit.SECONDS.sleep(2);
int i = 0;
if(i == 0){
throw new Exception("异常...");
}
System.out.println("MyCalableB end," + System.currentTimeMillis());
return "MyCalableB";
}
} public class Main { public static void main(String[] args) {
try {
MyCalableA myCalableA = new MyCalableA();
MyCalableB myCalableB = new MyCalableB();
Executor executor = Executors.newSingleThreadExecutor();
CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
completionService.submit(myCalableA);
completionService.submit(myCalableB);
for (int i = 0; i < 2; i++) {
System.out.println("----" + completionService.take());
}
System.out.println("main end");
} catch (Exception e) {
e.printStackTrace();
}
}
}

控制台打印结果如下:

MyCalableA begin,1471006680464
MyCalableA end,1471006682467
MyCalableB begin,1471006682467
----java.util.concurrent.FutureTask@3918d722
----java.util.concurrent.FutureTask@dd41677
main end

MyCalableB类中虽然跑出了异常,但是并没有调用GutureTask类的get()方法,所以不出现异常。

对以上代码做如下修改:

for (int i = 0; i < 2; i++) {
System.out.println("----" + completionService.take().get());
}

此时运行结果如下:

MyCalableA begin,1471007865642
MyCalableA end,1471007866647
MyCalableB begin,1471007866647
----MyCalableA
java.util.concurrent.ExecutionException: java.lang.Exception: 异常...
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:188)
at com.concurrent.chapter6.concurrent02.Main.main(Main.java:19)
Caused by: java.lang.Exception: 异常...
at com.concurrent.chapter6.concurrent02.MyCalableB.call(MyCalableB.java:14)
at com.concurrent.chapter6.concurrent02.MyCalableB.call(MyCalableB.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

MyCalableA先执行完,未抛出异常。MyCalableB线程抛出异常。

对以上代码做如下修改:

public class Main {

	public static void main(String[] args) {
try {
MyCalableA myCalableA = new MyCalableA();
MyCalableB myCalableB = new MyCalableB();
Executor executor = Executors.newSingleThreadExecutor();//单线程
CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
completionService.submit(myCalableB);//先执行B任务
completionService.submit(myCalableA);
for (int i = 0; i < 2; i++) {
System.out.println("----" + completionService.take().get());
}
System.out.println("main end");
} catch (Exception e) {
e.printStackTrace();
}
}
}

此时控制台输出结果如下:

MyCalableB begin,1471008229367
MyCalableA begin,1471008231370
java.util.concurrent.ExecutionException: java.lang.Exception: 异常...
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:188)
at com.concurrent.chapter6.concurrent02.Main.main(Main.java:19)
Caused by: java.lang.Exception: 异常...
at com.concurrent.chapter6.concurrent02.MyCalableB.call(MyCalableB.java:14)
at com.concurrent.chapter6.concurrent02.MyCalableB.call(MyCalableB.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
MyCalableA end,1471008232373

此时B任务抛出异常,A任务执行完但未返回值。

对以上代码继续做如下修改:

public class Main {

	public static void main(String[] args) {
try {
MyCalableA myCalableA = new MyCalableA();
MyCalableB myCalableB = new MyCalableB();
Executor executor = Executors.newSingleThreadExecutor();//单线程
CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
completionService.submit(myCalableA);//先执行A任务
completionService.submit(myCalableB);
for (int i = 0; i < 2; i++) {
System.out.println("----" + completionService.poll());
}
TimeUnit.SECONDS.sleep(5);
System.out.println("A处:" + completionService.poll());
System.out.println("B处:" + completionService.poll());
System.out.println("main end");
} catch (Exception e) {
e.printStackTrace();
}
}
}

此时运行结果如下:

----null
----null
MyCalableA begin,1471009161165
MyCalableA end,1471009162166
MyCalableB begin,1471009162166
A处:java.util.concurrent.FutureTask@5f0ee5b8
B处:java.util.concurrent.FutureTask@4b0bc3c9
main end

未调用get()方法,未抛出异常。

继续修改以上代码:

public class Main {

	public static void main(String[] args) {
try {
MyCalableA myCalableA = new MyCalableA();
MyCalableB myCalableB = new MyCalableB();
Executor executor = Executors.newSingleThreadExecutor();//单线程
CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
completionService.submit(myCalableA);//先执行A任务
completionService.submit(myCalableB);
for (int i = 0; i < 2; i++) {
System.out.println("----" + completionService.poll());
}
TimeUnit.SECONDS.sleep(5);
System.out.println("A处:" + completionService.poll().get());
System.out.println("B处:" + completionService.poll().get());
System.out.println("main end");
} catch (Exception e) {
e.printStackTrace();
}
}
}

控制台打印结果如下:

----null
----null
MyCalableA begin,1471009511872
MyCalableA end,1471009512876
MyCalableB begin,1471009512877
A处:MyCalableA
java.util.concurrent.ExecutionException: java.lang.Exception: 异常...
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:188)
at com.concurrent.chapter6.concurrent02.Main.main(Main.java:24)
Caused by: java.lang.Exception: 异常...
at com.concurrent.chapter6.concurrent02.MyCalableB.call(MyCalableB.java:14)
at com.concurrent.chapter6.concurrent02.MyCalableB.call(MyCalableB.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

此时A任务有返回值。B任务抛出异常,无返回值。

继续修改以上代码:

public class Main {

	public static void main(String[] args) {
try {
MyCalableA myCalableA = new MyCalableA();
MyCalableB myCalableB = new MyCalableB();
Executor executor = Executors.newSingleThreadExecutor();//单线程
CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
completionService.submit(myCalableB);//先执行B任务
completionService.submit(myCalableA);
for (int i = 0; i < 2; i++) {
System.out.println("----" + completionService.poll());
}
TimeUnit.SECONDS.sleep(5);
System.out.println("A处:" + completionService.poll().get());
System.out.println("B处:" + completionService.poll().get());
System.out.println("main end");
} catch (Exception e) {
e.printStackTrace();
}
}
}

运行结果如下:

----null
----null
MyCalableB begin,1471009732036
MyCalableA begin,1471009734037
MyCalableA end,1471009735037
java.util.concurrent.ExecutionException: java.lang.Exception: 异常...
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:188)
at com.concurrent.chapter6.concurrent02.Main.main(Main.java:23)
Caused by: java.lang.Exception: 异常...
at com.concurrent.chapter6.concurrent02.MyCalableB.call(MyCalableB.java:14)
at com.concurrent.chapter6.concurrent02.MyCalableB.call(MyCalableB.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

此时任务B抛出异常,任务A未打印。

Java并发编程核心方法与框架-CompletionService的使用的更多相关文章

  1. Java并发编程核心方法与框架-CountDownLatch的使用

    Java多线程编程中经常会碰到这样一种场景:某个线程需要等待一个或多个线程操作结束(或达到某种状态)才开始执行.比如裁判员需要等待运动员准备好后才发送开始指令,运动员要等裁判员发送开始指令后才开始比赛 ...

  2. Java并发编程核心方法与框架-Fork-Join分治编程(一)

    在JDK1.7版本中提供了Fork-Join并行执行任务框架,它的主要作用是把大任务分割成若干个小任务,再对每个小任务得到的结果进行汇总,这种开发方法也叫做分治编程,可以极大地利用CPU资源,提高任务 ...

  3. Java并发编程核心方法与框架-TheadPoolExecutor的使用

    类ThreadPoolExecutor最常使用的构造方法是 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAli ...

  4. Java并发编程核心方法与框架-Semaphore的使用

    Semaphore中文含义是信号.信号系统,这个类的主要作用就是限制线程并发数量.如果不限制线程并发数量,CPU资源很快就会被耗尽,每个线程执行的任务会相当缓慢,因为CPU要把时间片分配给不同的线程对 ...

  5. Java并发编程核心方法与框架-ScheduledExecutorService的使用

    类SchedukedExecutorService的主要作用是可以将定时任务与线程池功能结合. 使用Callable延迟运行(有返回值) public class MyCallableA implem ...

  6. Java并发编程核心方法与框架-ExecutorService的使用

    在ThreadPoolExecutor中使用ExecutorService中的方法 方法invokeAny()和invokeAll()具有阻塞特性 方法invokeAny()取得第一个完成任务的结果值 ...

  7. Java并发编程核心方法与框架-Future和Callable的使用

    Callable接口与Runnable接口对比的主要优点是Callable接口可以通过Future获取返回值.但是Future接口调用get()方法取得结果时是阻塞的,如果调用Future对象的get ...

  8. Java并发编程核心方法与框架-Executors的使用

    合理利用线程池能够带来三个好处 降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗. 提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行. 提高线程的可管理性.线程是稀 ...

  9. Java并发编程核心方法与框架-phaser的使用

    arriveAndAwaitAdvance()方法 arriveAndAwaitAdvance()作用是当前线程已经到达屏障,在此等待一段时间,等条件满足后继续向下一个屏障执行. public cla ...

随机推荐

  1. Mac OS 下 eclipse中文乱码解决方法(eclipse for mac 中文乱码)

    由于一些java源码是从其他人那里拷贝过来,放入Mac os 版本的eclipse下,发现中文都是乱码.经过小试,可以解决. 1.打开eclipse 偏好设置 2.General ——>Cont ...

  2. linux删除文件后没有释放空间

    转载 http://blog.csdn.net/wyzxg/article/details/4971843 今天发现一台服务器的home空间满了,于是要清空无用的文件,当我删除文件后,发现可用空间没有 ...

  3. watch监听 chechbox 全选

    // 监控全选checkbox的状态 $scope.$watch('AllCheck', function (newValue, oldValue) { // 第一次不执行 if (newValue ...

  4. Java并发和多线程(二)Executor框架

    Executor框架 1.Task?Thread? 很多人在学习多线程这部分知识的时候,容易搞混两个概念:任务(task)和线程(thread). 并发编程可以使我们的程序可以划分为多个分离的.独立运 ...

  5. 【BZOJ-3832】Rally 拓扑序 + 线段树 (神思路题!)

    3832: [Poi2014]Rally Time Limit: 20 Sec  Memory Limit: 128 MBSec  Special JudgeSubmit: 168  Solved:  ...

  6. jpa和hibernate注解

    http://www.objectdb.com/api/java/jpa/JoinColumns 用hibernate和jpa annotation 大概一年多了,今天闲来无事,对他们关联关系元数据写 ...

  7. PriorityQueue

    基本概念 顾名思义,PriorityQueue是优先级队列,它首先实现了队列接口(Queue),与LinkedList类似,它的队列长度也没有限制,与一般队列的区别是,它有优先级的概念,每个元素都有优 ...

  8. Codeforces 711E ZS and The Birthday Paradox

    传送门 time limit per test 2 seconds memory limit per test 256 megabytes input standard input output st ...

  9. AngularJs $interpolate 和 $parse

    $interpolate 将一个字符串编译成一个插值函数.HTML编译服务使用这个服务完成数据绑定. 使用:$interpolate(text,[mustHaveExpression],[truste ...

  10. 演示get、post请求如何算sn,算得sn如何使用

    import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.UnsupportedEncoding ...