Future 和 ExecutorCompletionService 对比和使用
附加:Java 4种线程池介绍请查看
谈谈new Thread的弊端及Java四种线程池的使用
当我们通过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) {
//超时异常直接忽略
//future.cancel(true);//超时设置任务取消
}
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 = 3;
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来完成。在构造函数中创建一个BlockingQueue来保存计算完成的结果,当提交某个任务时,该任务首先将被包装为一个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不存在元素时,这两个操作会阻塞,一旦有结果加入,则立即返回。
附加知识点:
take():取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到Blocking有新的对象被加入为止;
poll(time):取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回nul
public Future<V> take() throws InterruptedException {
return completionQueue.take();
}
public Future<V> poll() {
return completionQueue.poll();
}
Future 和 ExecutorCompletionService 对比和使用的更多相关文章
- 谈谈new Thread的弊端及Java四种线程池的使用
1.new Thread的弊端执行一个异步任务你还只是如下new Thread吗? new Thread(new Runnable() { @Override public void run() { ...
- JAVA多线程提高七:Callable与Future的应用
Callable与Runnable 先说一下java.lang.Runnable吧,它是一个接口,在它里面只声明了一个run()方法: public interface Runnable { publ ...
- JAVA多线程学习十-Callable与Future的应用
Callable与Runnable 先说一下java.lang.Runnable吧,它是一个接口,在它里面只声明了一个run()方法: public interface Runnable { publ ...
- 九 fork/join CompletableFuture
1: Fork/join fork/join: fork是分叉的意思, join是合并的意思. Fork/Join框架:是JAVA7提供的一个用于并行执行任务的框架,是一个把大任务分割成若干个小任务 ...
- Java线程之CompletionService批处理任务
如果你向Executor提交了一个批处理任务,并且希望在它们完成后获得结果,怎么办呢? 为此你可以保存与每个任务相关联的Future,然后不断地调用 timeout为零的get,来检验Future是否 ...
- 《java并发编程实战》读书笔记5--任务执行, Executor框架
第6章 任务执行 6.1 在线程中执行任务 第一步要找出清晰的任务边界.大多数服务器应用程序都提供了一种自然的任务边界选择方式:以独立的请求为边界. -6.6.1 串行地执行任务 最简单的任务调度策略 ...
- 使用CompletionService批处理任务(线程池阻塞线程)
CompletionService ExecutorService BlockingQueueFuture 如果你向Executor提交了一个批处理任务,并且希望在它们完成后获得结果.为此你可以保存与 ...
- 【并发那些事】线程有序化神器CompletionService
前言 话说有一天,产品经理突然找到正在摸鱼的你. 产品:『我们要加一个聚合搜索功能,当用户在我们网站查询一件商品时,我们分别从 A.B.C 三个网站上查询这个信息,然后再把得到的结果返回给用户』 你: ...
- java中CompletionService的使用
java中CompletionService的使用 之前的文章中我们讲到了ExecutorService,通过ExecutorService我们可以提交一个个的task,并且返回Future,然后通过 ...
随机推荐
- deb包+软件图标+添加到系统菜单+举例安装卸载
本文介绍的内容和实验一下: 1. 制造deb包.2. 为了使软件图标.3. 开始菜单中添加到系统中的软件:4. 安装和卸载制作的deb包. 1. 制作deb包 制作deb包的方法可能有多种,本文使用的 ...
- 【麦子学院】OpenCV教程函数总结
个自带样例. parter 1: No1. adaptiveskindetector.cpp 利用HSV空间的色调信息的皮肤检測,背景不能有太多与肤色相似的颜色.效果不是特别好. No2. bagof ...
- JavaScript继承基础讲解,原型链、借用构造函数、混合模式、原型式继承、寄生式继承、寄生组合式继承
说好的讲解JavaScript继承,可是迟迟到现在讲解.废话不多说,直接进入正题. 既然你想了解继承,证明你对JavaScript面向对象已经有一定的了解,如还有什么不理解的可以参考<面向对象J ...
- SQL点滴19—T-SQL中的透视和逆透视
原文:SQL点滴19-T-SQL中的透视和逆透视 透视 今天抽一点时间来看看透视和逆透视语句,简单的说就是行列转换.假设一个销售表中存放着产品号,产品折扣,产品价格三个列,每一种产品号可能有多种折扣, ...
- [Android] Volley源代码分析(五岁以下儿童)Q \\ u0026一个
Volley源代码分析系列那里一段时间,告诉我,有许多私人留言,同时一些问题抛出.对于一些简单的问题,我们跳,这两天被连接到朋友@smali提出的问题.告诉我你不得不赞叹查看源代码时的详细程度,大家一 ...
- APUE学习笔记(2):lseek()练习与文件洞
对于lseek函数早在大一的C语言课上就有接触,但是几乎没有使用过,只记得是和文件偏移操作相关的 看了APUE上的示例,又使用od工具查看了内容,果然很神奇,很新鲜 figure3.2.c [c] # ...
- leetcode第28题--Divide Two Integers
Divide two integers without using multiplication, division and mod operator. 分析:题目意思很容易理解,就是不用乘除法和模运 ...
- go orcale
golang连接orcale 使用glang有一段时间了,最开始其实并不太喜欢他的语法,但是后来熟悉之后发现用起来还挺爽的.之前数据库一直使用mysql,连接起来没有什么问题,github上有很多 ...
- Dynamics CRM 2013 体验
CRM 2013终于可以下载了,赶紧下载安装. 在CRM 2011 的基础上,CRM 2013 在UI上有了很大的变化.从CRM 2011 RollUp 12开始,微软就放弃了按钮的立体效果,逐渐趋向 ...
- JavaScript模板引擎原理
JavaScript模板引擎原理,几行代码的事儿 2013-12-03 16:35 by BarretLee, 650 阅读, 6 评论, 收藏, 编辑 一.前言 什么是模板引擎,说的简单点,就是一个 ...