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的使用的更多相关文章

  1. java高级---->Thread之ScheduledExecutorService的使用

    ScheduledExecutorService的主要作用就是可以将定时任务与线程池功能结合使用.今天我们来学习一下ScheduledExecutorService的用法.我们都太渺小了,那么容易便湮 ...

  2. java高级---->Thread之ExecutorService的使用

    今天我们通过实例来学习一下ExecutorService的用法.我徒然学会了抗拒热闹,却还来不及透悟真正的冷清. ExecutorService的简单实例 一.ExecutorService的简单使用 ...

  3. java高级---->Thread之Phaser的使用

    Phaser提供了动态增parties计数,这点比CyclicBarrier类操作parties更加方便.它是jdk1.7新增的类,今天我们就来学习一下它的用法.尘埃落定之后,回忆别来挑拨. Phas ...

  4. java高级---->Thread之CyclicBarrier的使用

    CyclicBarrier是一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point).今天我们就学习一下CyclicBarrier的用法. Cycl ...

  5. java高级---->Thread之BlockingQueue的使用

    今天我们通过实例来学习一下BlockingQueue的用法.梦想,可以天花乱坠,理想,是我们一步一个脚印踩出来的坎坷道路. BlockingQueue的实例 官方文档上的对于BlockingQueue ...

  6. java高级---->Thread之Exchanger的使用

    Exchanger可以在两个线程之间交换数据,只能是2个线程,他不支持更多的线程之间互换数据.今天我们就通过实例来学习一下Exchanger的用法. Exchanger的简单实例 Exchanger是 ...

  7. java高级---->Thread之FutureTask的使用

    FutureTask类是Future 的一个实现,并实现了Runnable,所以可通过Excutor(线程池) 来执行,也可传递给Thread对象执行.今天我们通过实例来学习一下FutureTask的 ...

  8. java高级---->Thread之Condition的使用

    Condition 将 Object 监视器方法(wait.notify 和 notifyAll)分解成截然不同的对象,以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set ...

  9. java高级---->Thread之CountDownLatch的使用

    CountDownLatch是JDK 5+里面闭锁的一个实现,允许一个或者多个线程等待某个事件的发生.今天我们通过一些实例来学习一下它的用法. CountDownLatch的简单使用 CountDow ...

随机推荐

  1. linux内核阻塞IO

    阻塞操作是指在执行设备操作时,若不能获得资源,则挂起进程直到满足可操作的条件后再进行操作.被挂起的进程进入休眠状态,被从调度器的运行队列移走,知道等待的条件被满足.而非阻塞的进程在不能进行设备操作时, ...

  2. zoj3228 Searching the String AC自动机查询目标串中模式串出现次数(分可覆盖,不可覆盖两种情况)

    /** 题目:zoj3228 Searching the String 链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=34 ...

  3. C# - 简单介绍TaskScheduler

    task Scheduler根据定义 The task Scheduler by the definition blurb. “Is the class where the usage context ...

  4. 利用百度地图API根据地址查询经纬度

    传上来只是为了记录下三种jsonp方式,$.get(url, callback)方式不行,会出错 -- 必须指明返回类型为”json”才行. 或者使用$.getJSON()或者$.ajax({}). ...

  5. lambda小结

    新公司用Java8,所以搜了下文档,发现其主要是两个概念:Lambda表达式和函数式接口. Lambda是一段可执行的代码(类似匿名函数). Lambda的设计者们为了让Java现有的体系与Lambd ...

  6. Oracle数据库表空间与用户的关系是 ( )

    Oracle数据库表空间与用户的关系是 ( )? A.一对一 B.一对多 C.多对一 D.多对多 解答: D 一个用户可以使用一个或多个表空间,一个表空间也可以供多个用户使用.

  7. Zookeeper 基础

    在深入了解ZooKeeper的运作之前,让我们来看看ZooKeeper的基本概念.我们将在本章中讨论以下主题:1.Architecture(架构)2.Hierarchical namespace(层次 ...

  8. html style的width不起作用

    一. 有些元素的默认情况下没有长度属性的,所以在其style内指定width属性是不会起作用的. 应对措施:使其浮动,float:left/right,浮动的元素长度和宽带都默认是0的,需要指定长度和 ...

  9. iOS7入门开发全系列教程新地址

    包括了系列1所有.系列2所有,系列3部分(进行中) 由于大家都知道的原因,换了github保存: https://github.com/eseedo/kidscoding 假设下载有问题能够留言,请在 ...

  10. vector deque list

    vector ,deque 和 list 顺序性容器: 向量 vector :   是一个线性顺序结构.相当于数组,但其大小可以不预先指定,并且自动扩展.它可以像数组一样被操作,由于它的特性我们完全可 ...