接口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. 【CodeForces 577C】Vasya and Petya’s Game

    链接 某个数x属于[1,n],至少询问哪些数“x是否是它的倍数”才能判断x.找出所有质因数和质因数的幂即可. #include<cstdio> #include<algorithm& ...

  2. 数组与指针-----a[i]=*(a+i)=i[a]

    #include<stdio.h> #include<stdlib.h> int main(void) { ,,,,};//a[i]相当于*(a+i) printf(]); p ...

  3. 面向对象_python

    面向对象_python 类(Class): 用来描述具有相同的属性和方法的对象的集合.它定义了该集合中每个对象所共有的属性和方法.对象是类的实例. 类变量:类变量在整个实例化的对象中是公用的.类变量定 ...

  4. kali2016.2源

    最近中科大的源出了问题,官方源又会重定向到意大利. 一下源目前亲测可用:kali2016.2源 清华大学 deb http://mirrors.tuna.tsinghua.edu.cn/kali ka ...

  5. gulp用途

    前端构建工具,可以实现文件合并.文件压缩.语法检查.监听文件变化 参看: http://blog.sina.com.cn/s/blog_6592d8070102vmuq.html https://se ...

  6. Linux学习路线

    为什么要学习Linux? 为什么学Linux,每个人都有自己的理由: Linux是免费的不用花一分钱,能够节约大笔的成本: Linux是开源的,你可以根据自已的需要修改源代码: Linux是开放的,有 ...

  7. Python基础1:if条件判断 break/continue语句

    计算机之所以能做很多自动化的任务,因为它可以自己做条件判断. Python中,if语句被用来进行判断,它的语法结构是: 1 if 判断条件: 2 执行语句…… 3 var = input(" ...

  8. HDU4612 Warm up

    Time Limit: 5000MS   Memory Limit: 65535KB   64bit IO Format: %I64d & %I64u Description N planet ...

  9. Refresh和Invalidate的比较

    Refresh: 强制控件使其工作区无效并立即重绘自己和任何子控件.==Invalidate + Update Invalidate: 使控件的特定区域(可以自己设置区域,从而提高性能)无效并向控件发 ...

  10. .net中ckeditor的应用

    ①js文件的引入 <script src="/public/ckeditor_4.4.7/ckeditor.js"></script> <script ...