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 ...
随机推荐
- git学习(四):理解git暂存区(stage)
与一般的版本管理不同的是,git在提交之前要将更改通过git add 添加到暂存区才能提交(git commit).即使是已经交给了git来管理的文件也是如此.这里继续学习git的暂存区. 通过git ...
- mysql的onestart和start区别
在FreeBSD上安装了mysql5.7之后,启动mysql时报了如下的错误: root@tuhooo:~ # /usr/local/etc/rc.d/mysql-server start Canno ...
- iio adc转换应用编写
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> # ...
- 【高可用HA】Apache (4) —— Mac下配置Apache Httpd负载均衡(Load Balancer)之mod_jk
Mac下配置Apache Httpd负载均衡(Load Balancer)之mod_jk httpd版本: httpd-2.4.17 jk版本: tomcat-connectors-1.2.41 参考 ...
- CentOS5.4安装redmine详细步骤
>>>>概述<<<< 这里不解释什么是redmine及用来做什么,如果不知道用来做什么,估计也不会把它安装到CentOS5.4上.哈哈…… 以下为详细的 ...
- 使用MultipartEntity上传文件(带进度对话框)
package com.home.uploadfile; import java.io.File; import android.app.Activity; import android.os.Bun ...
- tensorflow函数学习笔记
https://www.w3cschool.cn/tensorflow_python/tensorflow_python-4isv2ez3.html tf.trainable_variables返回的 ...
- http的GET和POST
本文主要内容 1. GET和POST方法介绍 2. 源代码分析 3. 结果分析 4. 例子参考及引用: http://www.cnblogs.com/zhijianliutang/archiv ...
- bson.errors.InvalidStringData: strings in documents must be valid UTF-8
场景: pymongo 查询数据库的时候报错. for gscode in GSList_StockPool_Mongo_MktStop: self._collection_flash.find({& ...
- linux gzip 命令详解
减少文件大小有两个明显的好处,一是可以减少存储空间,二是通过网络传输文件时,可以减少传输的时间.gzip是在Linux系统中经常使用的一个对文件进行压缩和解压缩的命令,既方便又好用. 语法:gzip ...