Callable接口和Future
本篇说明的是Callable和Future,它俩很有意思的,一个产生结果,一个拿到结果。
Callable接口类似于Runnable,从名字就可以看出来了,但是Runnable不会返回结果,并且无法抛出返回结果的异常,而Callable功能更强大一些,被线程执行后,可以返回值,这个返回值可以被Future拿到,也就是说,Future可以拿到异步执行任务的返回值,下面来看一个简单的例子:
public class CallableAndFuture {
public static void main(String[] args) {
Callable<Integer> callable = new Callable<Integer>() {
public Integer call() throws Exception {
return new Random().nextInt(100);
}
};
FutureTask<Integer> future = new FutureTask<Integer>(callable);
new Thread(future).start();
try {
Thread.sleep(5000);// 可能做一些事情
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
FutureTask实现了两个接口,Runnable和Future,所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值,那么这个组合的使用有什么好处呢?假设有一个很耗时的返回值需要计算,并且这个返回值不是立刻需要的话,那么就可以使用这个组合,用另一个线程去计算返回值,而当前线程在使用这个返回值之前可以做其它的操作,等到需要这个返回值时,再通过Future得到,岂不美哉!这里有一个Future模式的介绍:http://openhome.cc/Gossip/DesignPattern/FuturePattern.htm。
下面来看另一种方式使用Callable和Future,通过ExecutorService的submit方法执行Callable,并返回Future,代码如下:
public class CallableAndFuture {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<Integer> future = threadPool.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return new Random().nextInt(100);
}
});
try {
Thread.sleep(5000);// 可能做一些事情
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
代码是不是简化了很多,ExecutorService继承自Executor,它的目的是为我们管理Thread对象,从而简化并发编程,Executor使我们无需显示的去管理线程的生命周期,是JDK 5之后启动任务的首选方式。
执行多个带返回值的任务,并取得多个返回值,代码如下:
public class CallableAndFuture {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newCachedThreadPool();
CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);
for(int i = 1; i < 5; i++) {
final int taskID = i;
cs.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return taskID;
}
});
}
// 可能做一些事情
for(int i = 1; i < 5; i++) {
try {
System.out.println(cs.take().get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
其实也可以不使用CompletionService,可以先创建一个装Future类型的集合,用Executor提交的任务返回值添加到集合中,最后遍历集合取出数据
参考代码:
package com.jd.test; import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*; public class CallableTest4 {
public static void main(String[] args) {
ExecutorService es= Executors.newCachedThreadPool();
List<Future<Integer>> futureList=new ArrayList<Future<Integer>>();
for(int i=0;i<10;i++) {
Future<Integer> integerFuture = es.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return new Random().nextInt(100);
}
});
futureList.add(integerFuture);
}
try {
System.out.println("系统兼职开始~");
Thread.sleep(5000);// 可能做一些事情
System.out.println("系统兼职结束~");
for(Future<Integer> futureInteger:futureList){
System.out.println("回到先前的任务 随机数为:"+futureInteger.get());
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
提交到CompletionService中的Future是按照完成的顺序排列的,而Lisr这种做法中Future是按照添加的顺序排列的。
参考链接:http://blog.csdn.net/ghsau/article/details/7451464
Callable接口和Future的更多相关文章
- Java Callable接口与Future接口的两种使用方式
Java Callable.Future的两种使用方式Callable+Futurepublic class Test { public static void main(String[] args) ...
- Callable接口、Runable接口、Future接口
1. Callable与Runable区别 Java从发布的第一个版本开始就可以很方便地编写多线程的应用程序,并在设计中引入异步处理.Thread类.Runnable接口和Java内存管理模型使得多线 ...
- Java Callable接口、Runable接口、Future接口
1. Callable与Runable区别 Java从发布的第一个版本开始就可以很方便地编写多线程的应用程序,并在设计中引入异步处理.Thread类.Runnable接口和Java内存管理模型使得多线 ...
- Future接口和Callable接口以及FeatureTask详解
类继承关系 Callable接口 @FunctionalInterface public interface Callable<V> { V call() throws Exception ...
- 实现Callable接口,并与Future结合使用
实现步骤: 创建 Callable 接口的实现类,并实现 call() 方法,该 call() 方法将作为线程执行体,并且有返回值. 创建 Callable 实现类的实例,使用 FutureTask ...
- 线程池的应用及Callable接口的使用
public interface Executor { /** * Executes the given command at some time in the future. The comman ...
- [改善Java代码]异步运算考虑使用Callable接口
多线程有两种实现方式: 一种是实现Runnable接口,另一种是继承Thread类,这两种方式都有缺点,run方法没有返回值,不能抛出异常(这两个缺点归根到底是Runable接口的缺陷,Thread也 ...
- 多线程——实现Callable接口
前两篇博客(多线程--继承Thread类.多线程--实现Runnable接口 )介绍了java使用线程的两种方法.这篇博客继续介绍第三种方法--实现Callable接口. 先说一下Runnable和C ...
- Java多线程之Callable接口的实现
Callable 和 Future接口 Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务. Callable和Runn ...
随机推荐
- ide fix pack for delph 10.2.3发布了
http://andy.jgknet.de/blog/ide-tools/ide-fix-pack/ IDE Fix Pack是RAD Studio IDE,Win32 / Win64 / Andoi ...
- Linux rm的一次误用
今天在Linux下误用了一次rm -rf,经历惨痛,记录一下. 原因是我删除了一个文件到回收站,然后点错了将home下的所有东西都删到了回收站,然后我又从回收站拷贝回home目录而不是使用恢复,因为h ...
- Python 文件复制_bytes
f1 = open("c:/huyifei.jpg", mode="rb") f2 = open("d:/huerfei.jpg", mod ...
- 阿里、华为、腾讯Java技术面试题精选
阿里.华为.腾讯Java技术面试题精选 2017-10-27 19:30技术/腾讯/华为 JVM的类加载机制是什么?有哪些实现方式? 类加载机制: 类的加载指的是将类的.class文件中的二进制数据读 ...
- springloaded hot deploy
download springloaded jar file -Dfile.encoding=utf-8 -javaagent:e:\\libs\\springloaded-1.2.5.jar -no ...
- RESTful API 学习
/********************************************************************************* * RESTful API 学习 ...
- 【error】no type named ‘type’ in ‘class std::result_of<void
Q: std::thread fs_module(fs_process, prob_orig, fb_sz, line_num, probp, plabel, std::ref(confidence_ ...
- Ubuntu 16.04下指定Sublime Text 3 默认python编译版本
安装PackageResourceViewer插件 输入 Ctrl+Shift+P 输入install,选择Package Control: Install Package 选择PackageReso ...
- php取浮点数后两位的方法
$num = 10.4567; //第一种:利用round()对浮点数进行四舍五入echo round($num,2); //10.46 //第二种:利用sprintf格式化字符串$format_nu ...
- leetcode -day28 Unique Binary Search Trees I II
1. Unique Binary Search Trees II Given n, generate all structurally unique BST's (binary search t ...