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 ...
随机推荐
- array_merge、array_merge_recursive
原文:http://www.111cn.net/phper/php/61889.htm 我在php学习在使用到最多的数据合并方法就是array_merge.array_merge_recursi ...
- Xcode清理垃圾
摘抄自https://blog.csdn.net/hu434587115/article/details/54602449 ~/Library/Developer/Xcode/DerivedData/ ...
- 在python中的使用
操作步骤: 1. 连接数据库,生成数据库连接对象 conn = pymongo.MongoClient('localhost',27017) 2. 选择要操作的数据库,生成数据库对象 (__setit ...
- 2N7002
就相当于一个开关,当G>S的一定电压就导通,若没有达到就没有导通. 并且注意的是D脚不能直接接电压,中间要接一个电阻. 这用是G输入,S接地,D输出. 跟三极管差不多.分N和P
- 教你正确进入DFU及恢复模式 无敌重刷模式
苹果分为两种恢复模式,一种叫做DFU模式,另一种是恢复模式.DFU的全称是Development FirmwareUpgrade,实际意思就是iPhone固件的强制升降级模式.而恢复模式则是屏幕上会显 ...
- 20155224 2016-2017-2 《Java程序设计》第5周学习总结
20155224 2016-2017-2 <Java程序设计>第5周学习总结 教材学习内容总结 第八章 Java中的错误都会被打包为对象,可以尝试(try)捕捉(catch)代表错误的对象 ...
- centos yum出现no module named yum
运行yum出现如下错误 There was a problem importing one of the Python modules required to run yum. The error l ...
- div+css 怎么让一个小div在另一个大div里面 垂直居中
div+css 怎么让一个小div在另一个大div里面 垂直居中 方法1: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 .parent { width:800 ...
- php empty详解
判断字符串是否为空,可以这么判断: if ($value=="") ... * 格式:bool empty ( mixed var ) * 功能:检查一个变量是否为空 ...
- vs2013下OpenGL环境的配置
1.下载glut库:https://files.cnblogs.com/files/laoxia/glutdlls37beta.zip 2.解压后,将glut.lib和glut32.lib两个文件拷贝 ...