java高级---->Thread之CompletionService的使用
CompletionService的功能是以异步的方式一边生产新的任务,一边处理已完成任务的结果,这样可以将执行任务与处理任务分离开来进行处理。今天我们通过实例来学习一下CompletionService的用法。
CompletionService的简单使用
使用submit()方法执行任务,使用take取得已完成的任务,并按照完成这些任务的时间顺序处理它们的结果。
一、CompletionService的submit方法
public class CompletionServiceTest {
public static void main(String[] args) throws Exception {
ExecutorService service = Executors.newFixedThreadPool(5);
CompletionService<String> completionService = new ExecutorCompletionService<String>(service);
for (int i = 0; i < 5; i++) {
completionService.submit(new ReturnAfterSleepCallable(i));
}
System.out.println("after submit");
for (int i = 0; i < 5; i++) {
System.out.println("result: " + completionService.take().get()); // 这个方法是阻塞的
}
System.out.println("after get");
service.shutdown();
}
private static class ReturnAfterSleepCallable implements Callable<String> {
int sleep;
public ReturnAfterSleepCallable(int sleep) {
this.sleep = sleep;
}
@Override
public String call() throws Exception {
TimeUnit.SECONDS.sleep(sleep);
return System.currentTimeMillis() + ",sleep=" + String.valueOf(sleep);
}
}
}
运行的结果如下:
after submit
result: ,sleep=
result: ,sleep=
result: ,sleep=
result: ,sleep=
result: ,sleep=
after get
官方文档上的说明:
Submits a value-returning task for execution and returns a Future representing the pending results of the task. Upon completion, this task may be taken or polled.
二、使用CompletionService的take方法
take()方法取得最先完成任务的Future对象,谁执行时间最短谁最先返回。
package com.linux.thread; import java.util.Random;
import java.util.concurrent.*; public class RunMain1 {
public static void main(String[] args) {
try {
ExecutorService executorService = Executors.newCachedThreadPool();
ExecutorCompletionService<String> completionService = new ExecutorCompletionService<>(executorService);
for (int i = 0; i < 10; i++) {
completionService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
int sleepValue = new Random().nextInt(5);
System.out.println("sleep = " + sleepValue + ", name: " + Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(sleepValue);
return "huhx: " + sleepValue + ", " + Thread.currentThread().getName();
}
});
}
for (int i = 0; i < 10; i++) {
System.out.println(completionService.take().get());
}
executorService.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
一次的运行结果如下:
sleep = , name: pool--thread-
sleep = , name: pool--thread-
sleep = , name: pool--thread-
huhx: , pool--thread-
huhx: , pool--thread-
sleep = , name: pool--thread-
sleep = , name: pool--thread-
sleep = , name: pool--thread-
sleep = , name: pool--thread-
sleep = , name: pool--thread-
huhx: , pool--thread-
sleep = , name: pool--thread-
sleep = , name: pool--thread-
huhx: , pool--thread-
huhx: , pool--thread-
huhx: , pool--thread-
huhx: , pool--thread-
huhx: , pool--thread-
huhx: , pool--thread-
huhx: , pool--thread-
官方文档上的说明:
Retrieves and removes the Future representing the next completed task, waiting if none are yet present.
三、使用CompletionService的poll方法
方法poll的作用是获取并移除表示下一个已完成任务的Future,如果不存在这样的任务,则返回null,方法poll是无阻塞的。
package com.linux.thread;
import java.util.concurrent.*;
public class RunMain2 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
CompletionService<String> service = new ExecutorCompletionService<String>(executorService);
service.submit(new Callable<String>() {
@Override
public String call() throws Exception {
TimeUnit.SECONDS.sleep(3);
System.out.println("3 seconds pass.");
return "3秒";
}
});
System.out.println(service.poll());
executorService.shutdown();
}
}
运行的结果如下:
null
seconds pass.
官方文档上的说明:
Retrieves and removes the Future representing the next completed task or null if none are present.
友情链接
java高级---->Thread之CompletionService的使用的更多相关文章
- java高级---->Thread之ScheduledExecutorService的使用
ScheduledExecutorService的主要作用就是可以将定时任务与线程池功能结合使用.今天我们来学习一下ScheduledExecutorService的用法.我们都太渺小了,那么容易便湮 ...
- java高级---->Thread之ExecutorService的使用
今天我们通过实例来学习一下ExecutorService的用法.我徒然学会了抗拒热闹,却还来不及透悟真正的冷清. ExecutorService的简单实例 一.ExecutorService的简单使用 ...
- java高级---->Thread之Phaser的使用
Phaser提供了动态增parties计数,这点比CyclicBarrier类操作parties更加方便.它是jdk1.7新增的类,今天我们就来学习一下它的用法.尘埃落定之后,回忆别来挑拨. Phas ...
- java高级---->Thread之CyclicBarrier的使用
CyclicBarrier是一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point).今天我们就学习一下CyclicBarrier的用法. Cycl ...
- java高级---->Thread之BlockingQueue的使用
今天我们通过实例来学习一下BlockingQueue的用法.梦想,可以天花乱坠,理想,是我们一步一个脚印踩出来的坎坷道路. BlockingQueue的实例 官方文档上的对于BlockingQueue ...
- java高级---->Thread之Exchanger的使用
Exchanger可以在两个线程之间交换数据,只能是2个线程,他不支持更多的线程之间互换数据.今天我们就通过实例来学习一下Exchanger的用法. Exchanger的简单实例 Exchanger是 ...
- java高级---->Thread之FutureTask的使用
FutureTask类是Future 的一个实现,并实现了Runnable,所以可通过Excutor(线程池) 来执行,也可传递给Thread对象执行.今天我们通过实例来学习一下FutureTask的 ...
- java高级---->Thread之Condition的使用
Condition 将 Object 监视器方法(wait.notify 和 notifyAll)分解成截然不同的对象,以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set ...
- java高级---->Thread之CountDownLatch的使用
CountDownLatch是JDK 5+里面闭锁的一个实现,允许一个或者多个线程等待某个事件的发生.今天我们通过一些实例来学习一下它的用法. CountDownLatch的简单使用 CountDow ...
随机推荐
- GNU make学习笔记
第五章:规则的命令 5.1 命令的回显 make在执行命令之前会把要执行的命令输出到标准输出设备,称之为"回显". 如果规则的命令以字符"@"开始,则make在 ...
- STM32F10x_ADC三通道逐次转换(单次、单通道软件触发)
Ⅰ.概述 本文讲述关于STM32功能比较强大的ADC模块.ADC(Analog to Digital Converter)也就是模拟量转化为数字量,而STM32的ADC模块功能比较多,本文主要讲述“三 ...
- ExtJs 常用小技巧备忘录
1. ExtJs 给fieldLabel与fieldInput添加样式{给Input标签加入图标}http://www.w3school.com.cn/cssref/pr_background.asp ...
- java基础复习二——面向对象一
面向对象三大特性:封装,继承,多态 类:对象的蓝图,生成对象的模板,是对一类事物的描述,是抽象的概念上的定义 对象:是实际存在的该类事物的每个个体,也称为实例 类之间三种关系:依赖关系(uses-a) ...
- [oracle] oracle权限传递
三个用户:SYS.lisi.wangwu ① 系统权限的传递 lisi的初始化系统权限 SQL> select * from user_sys_privs; USERNAME PRIVILEGE ...
- HBase二级索引方案总结
转自:http://blog.sina.com.cn/s/blog_4a1f59bf01018apd.html 附hbase如何创建二级索引以及创建二级索引实例:http://www.aboutyun ...
- 关于Unity中的NGUI和UGUI
一.用Unity开发2D游戏,有三套关系 1.GUI:Unity本身自带的GUI 2.NGUI:以前在Unity中广泛来做2D的,是第三方的包,需要安装 3.UGUI:Unity5.X后(其实是Uni ...
- selenium测试(Java)--执行JS(十八)
1. 操作滚动条 package com.test.js; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; ...
- wex5中集成的mysql数据库 打开时一闪而过 报错
在进程中kill mysql.exe 重新启动即可
- 第二百八十八节,MySQL数据库-索引、limit分页、执行计划、慢日志查询
MySQL数据库-索引.limit分页.执行计划.慢日志查询 索引,是数据库中专门用于帮助用户快速查询数据的一种数据结构.类似于字典中的目录,查找字典内容时可以根据目录查找到数据的存放位置,然后直接获 ...