Java利用future及时获取多线程运行结果
作者:clare-chen 发布时间:2022-02-18 21:57:30
标签:java,多线程,future
Future接口是Java标准API的一部分,在java.util.concurrent包中。Future接口是Java线程Future模式的实现,可以来进行异步计算。
有了Future就可以进行三段式的编程了,1.启动多线程任务2.处理其他事3.收集多线程任务结果。从而实现了非阻塞的任务调用。在途中遇到一个问题,那就是虽然能异步获取结果,但是Future的结果需要通过isdone来判断是否有结果,或者使用get()函数来阻塞式获取执行结果。这样就不能实时跟踪其他线程的结果状态了,所以直接使用get还是要慎用,最好配合isdone来使用。
这里有一种更好的方式来实现对任意一个线程运行完成后的结果都能及时获取的办法:使用CompletionService,它内部添加了阻塞队列,从而获取future中的值,然后根据返回值做对应的处理。一般future使用和CompletionService使用的两个测试案例如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* 多线程执行,异步获取结果
*
* @author i-clarechen
*
*/
public class AsyncThread {
public static void main(String[] args) {
AsyncThread t = new AsyncThread();
List<Future<String>> futureList = new ArrayList<Future<String>>();
t.generate(3, futureList);
t.doOtherThings();
t.getResult(futureList);
}
/**
* 生成指定数量的线程,都放入future数组
*
* @param threadNum
* @param fList
*/
public void generate(int threadNum, List<Future<String>> fList) {
ExecutorService service = Executors.newFixedThreadPool(threadNum);
for (int i = 0; i < threadNum; i++) {
Future<String> f = service.submit(getJob(i));
fList.add(f);
}
service.shutdown();
}
/**
* other things
*/
public void doOtherThings() {
try {
for (int i = 0; i < 3; i++) {
System.out.println("do thing no:" + i);
Thread.sleep(1000 * (new Random().nextInt(10)));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 从future中获取线程结果,打印结果
*
* @param fList
*/
public void getResult(List<Future<String>> fList) {
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(getCollectJob(fList));
service.shutdown();
}
/**
* 生成指定序号的线程对象
*
* @param i
* @return
*/
public Callable<String> getJob(final int i) {
final int time = new Random().nextInt(10);
return new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(1000 * time);
return "thread-" + i;
}
};
}
/**
* 生成结果收集线程对象
*
* @param fList
* @return
*/
public Runnable getCollectJob(final List<Future<String>> fList) {
return new Runnable() {
public void run() {
for (Future<String> future : fList) {
try {
while (true) {
if (future.isDone() && !future.isCancelled()) {
System.out.println("Future:" + future
+ ",Result:" + future.get());
break;
} else {
Thread.sleep(1000);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
}
}
运行结果打印和future放入列表时的顺序一致,为0,1,2:
do thing no:0
do thing no:1
do thing no:2
Future:java.util.concurrent.FutureTask@68e1ca74,Result:thread-0
Future:java.util.concurrent.FutureTask@3fb2bb77,Result:thread-1
Future:java.util.concurrent.FutureTask@6f31a24c,Result:thread-2
下面是先执行完的线程先处理的方案:
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
public class testCallable {
public static void main(String[] args) {
try {
completionServiceCount();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
/**
* 使用completionService收集callable结果
* @throws ExecutionException
* @throws InterruptedException
*/
public static void completionServiceCount() throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newCachedThreadPool();
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(
executorService);
int threadNum = 5;
for (int i = 0; i < threadNum; i++) {
completionService.submit(getTask(i));
}
int sum = 0;
int temp = 0;
for(int i=0;i<threadNum;i++){
temp = completionService.take().get();
sum += temp;
System.out.print(temp + "\t");
}
System.out.println("CompletionService all is : " + sum);
executorService.shutdown();
}
public static Callable<Integer> getTask(final int no) {
final Random rand = new Random();
Callable<Integer> task = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int time = rand.nextInt(100)*100;
System.out.println("thead:"+no+" time is:"+time);
Thread.sleep(time);
return no;
}
};
return task;
}
}
运行结果为最先结束的线程结果先被处理:
thead:0 time is:4200
thead:1 time is:6900
thead:2 time is:2900
thead:3 time is:9000
thead:4 time is:7100
0 1 4 3 CompletionService all is : 10
来源:http://www.cnblogs.com/clarechen/p/4604189.html


猜你喜欢
- 本文章从头开始介绍Spring集成Redis的示例。Eclipse工程结构如下图为我的示例工程的结构图,采用Maven构建。其中需要集成Sp
- 本文实例讲述了C#判断字符串是否存在字母及字符串中字符的替换的方法。分享给大家供大家参考。具体实现方法如下:首先要添加对命名空间“using
- import java.util.Arrays;public class HeapSort { publ
- 概述Kryo 是一个快速序列化/反序列化工具,依赖于字节码生成机制(底层使用了 ASM 库),因此在序列化速度上有一定的优势,但正因如此,其
- java 泛型方法:泛型是什么意思在这就不多说了,而Java中泛型类的定义也比较简单,例如:public class Test
- Java 两种延时thread和timer详解及实例代码在Java中有时候需要使程序暂停一点时间,称为延时。普通延时用Thread.slee
- 1. 前言Android LayerDrawble 包含一个Drawable数组,系统将会按照这些Drawable对象的数组顺序来绘制他们,
- 打开idea项目后部分目录下出现橙色的时钟标志(如下):可以看到所有的java文件都显示了后缀名.java,文件的图标都变成了橙色的原因项目
- 在 Java 语言中,运算符有算数运算符、关系运算符、逻辑运算符、赋值运算符、字符串连接运算符、条件运算符。算数运算符算数运算符是我们最常用
- java后端介绍今天我正式开始了一个新话题,那就是 Web。目前我主要会介绍后端。作为后端的老大哥 java,也有很多后端框架,比如大家耳熟
- 本文实例讲述了C++编写DLL动态链接库的步骤与实现方法。分享给大家供大家参考,具体如下:在写C++程序时,时常需要将一个class写成DL
- 1.更新MAC地址 将注册表中的键值添加上MAC地址2.重新连接网络 试过了3个方法: Ma
- 前言我们平时在开发中,难免会遇到一些比较特殊的需求,就比如我们这篇文章的主题,一个关于圆弧滑动的,一般是比较少见的。其实在遇到这些东西时,不
- 本文实例为大家分享了Android购物分类效果展示的具体代码,供大家参考,具体内容如下SecondActivity.javapublic c
- 一、线程的状态NEW: 安排了工作, 还未开始行动RUNNABLE: 可工作的. 又可以分成正在工作中和即将开始工作.BLOCKED: 这几
- 一、线程异常我们在单线程中,捕获异常可以使用try-catch,代码如下所示:using System;namespace Multithr
- 本文实例为大家分享了java实现猜拳游戏的具体代码,供大家参考,具体内容如下package com.farsight.session7;im
- 前言数字时间戳技术是数字签名技术一种变种的应用。是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08
- Service是什么 Service是一个android 系统中的应用程序组件,它跟Activity的级别差不多,但是他没有图形化界面,不能
- 文章描述以下主要还是使用到了ffmpeg命令,分别实现了给视频添加图片水印以及文字水印。开发环境.NET Framework版本:4.5开发