Java并发编程核心方法与框架-CompletionService的使用
接口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的使用的更多相关文章
- Java并发编程核心方法与框架-CountDownLatch的使用
Java多线程编程中经常会碰到这样一种场景:某个线程需要等待一个或多个线程操作结束(或达到某种状态)才开始执行.比如裁判员需要等待运动员准备好后才发送开始指令,运动员要等裁判员发送开始指令后才开始比赛 ...
- Java并发编程核心方法与框架-Fork-Join分治编程(一)
在JDK1.7版本中提供了Fork-Join并行执行任务框架,它的主要作用是把大任务分割成若干个小任务,再对每个小任务得到的结果进行汇总,这种开发方法也叫做分治编程,可以极大地利用CPU资源,提高任务 ...
- Java并发编程核心方法与框架-TheadPoolExecutor的使用
类ThreadPoolExecutor最常使用的构造方法是 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAli ...
- Java并发编程核心方法与框架-Semaphore的使用
Semaphore中文含义是信号.信号系统,这个类的主要作用就是限制线程并发数量.如果不限制线程并发数量,CPU资源很快就会被耗尽,每个线程执行的任务会相当缓慢,因为CPU要把时间片分配给不同的线程对 ...
- Java并发编程核心方法与框架-ScheduledExecutorService的使用
类SchedukedExecutorService的主要作用是可以将定时任务与线程池功能结合. 使用Callable延迟运行(有返回值) public class MyCallableA implem ...
- Java并发编程核心方法与框架-ExecutorService的使用
在ThreadPoolExecutor中使用ExecutorService中的方法 方法invokeAny()和invokeAll()具有阻塞特性 方法invokeAny()取得第一个完成任务的结果值 ...
- Java并发编程核心方法与框架-Future和Callable的使用
Callable接口与Runnable接口对比的主要优点是Callable接口可以通过Future获取返回值.但是Future接口调用get()方法取得结果时是阻塞的,如果调用Future对象的get ...
- Java并发编程核心方法与框架-Executors的使用
合理利用线程池能够带来三个好处 降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗. 提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行. 提高线程的可管理性.线程是稀 ...
- Java并发编程核心方法与框架-phaser的使用
arriveAndAwaitAdvance()方法 arriveAndAwaitAdvance()作用是当前线程已经到达屏障,在此等待一段时间,等条件满足后继续向下一个屏障执行. public cla ...
随机推荐
- Get it,你离几何达人不远了!
对于爱学几何的人,是否存在这样的困扰:没有标准的尺规工具,图形画的不标准,理解上总是出错......整天在纸上画图,浪费大把大把的时间......几何图形画的不美观,在别人面前都拿不出手,公开课上都没 ...
- 最新版CocoaPods的使用与安装-以导入ReactiveCocoa框架为例
一.什么是CocoaPods?前言: 思考如何引入一个第三方框架. 例如: 百度地图SDK.友盟.ShareSDK. 信鸽推送等.从github或某处下载第三方SDK工程中导入所需要的SDK的文件 . ...
- 面向对象_python
面向对象_python 类(Class): 用来描述具有相同的属性和方法的对象的集合.它定义了该集合中每个对象所共有的属性和方法.对象是类的实例. 类变量:类变量在整个实例化的对象中是公用的.类变量定 ...
- Redis集合-Set
sadd 向一个Set中添加数据 127.0.0.1:6379> sadd set01 1 1 2 2 3 3 (integer) 3127.0.0.1:6379> SMEMBERS se ...
- NOI题库分治算法刷题记录
今天晚自习机房刷题,有一道题最终WA掉两组,极其不爽,晚上回家补完作业欣然搞定它,特意来写篇博文来记录下 (最想吐槽的是这个叫做分治的分类,里面的题目真的需要分治吗...) 先来说下分治法 分治法的设 ...
- text-indent无效解决方案
text-indent是用来字符缩进的. 1.text-indent所在的元素是行内元素而非块级元素.比如用在span,a等行内元素上.解决方案:在行内元素加上display:block; 或者把目标 ...
- 数组内部对象排序(sort)
1.数组排序有很多方法比如for,while循环去进行冒泡排序或者快速看.排序等多种排序方法 而我在这里要说的是苹果API提供的几个系统方法 a.迭代器 Descriptor b.方法比较 ...
- 数据结构算法C语言实现(七)--- 3.1栈的线性实现及应用举例
一.简述 栈,LIFO.是操作受限的线性表,和线性表一样有两种存储表示方法.下面以顺序存储为例,实现. 二.ADT 暂无. 三.头文件 //3_1.h /** author:zhaoyu email: ...
- 帝国cms栏目自定义字段首页调用
例如:增加栏目自定义字段:chushi_bpic 用下面的灵动标签和调用: [e:loop={"select C.classid,C.classname,C.classimg,D.chush ...
- STL之lower_bound和upper_bound
ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法返回一个非递减序列[first, la ...