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 ...
随机推荐
- apache的<directory> 语句以及属性的含义
在整完apache和tomcat的之后我觉得有必要把<directory>和它下面的属性捋顺一下 如何访问根目录下的目录http://192.168.1.12/test/ 第一.缺省apa ...
- jquery日期和时间的插件精确到秒
首先.html5提供了input的time类型,使我们可以通过input框输入日期,但是如果我们的需求是这个时间需要明确到几时几分几秒的,那html5就没有办法满足我们的需求了,就需要使用jQuery ...
- UI基础:UIControl及其子类
UISegmentedControl UISegmentedControl 是iOS中的分段控件 每个segment 都能被点击,相当于集成了若干个button. 通常我们会点击不同的segment ...
- UML-(团队作业)
UML设计 1.团队信息: 队名:异次元 2.团队成员: 姓名 分配任务 王诚荣(队长) 汇总合并,系统活动图 马祎特 好感度系统类图,电子版图片绘制 陈斌 个人中心,闹钟界面用例图,状态图 洪康 后 ...
- Unity3D插件-自制小插件、简化代码便于使用(新手至高手进阶必经之路)
Unity3D插件-简化代码.封装功能 本文提供全流程,中文翻译.Chinar坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) 1 FindT() ...
- 51Nod:1003 阶乘后面0的数量
1003 阶乘后面0的数量 基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题 收藏 关注 n的阶乘后面有多少个0? 6的阶乘 = 1*2*3*4*5*6 = 72 ...
- (2)socket的基础使用(基于TCP协议)
socket()模块函数用法 基于TCP协议的套接字程序 netstart -an | findstr 8080 #查看所有TCP和UDP协议的状态,用findstr进行过滤监听8080端口 服务端套 ...
- 在各OJ上的名号
POJ MekakuCityActors 牛客 MekakuCityActors hdoj MekakuCityActors 这几个难度较大,所以用Actors 博客 MekakuCityActor ...
- call和apply的意义和区别
区别在于 call 的第二个参数可以是任意类型,而apply的第二个参数必须是数组 如 func.call(func1,var1,var2,var3)对应的apply写法为:func.apply(f ...
- Web Js推断键盘出发事件
window.document.onkeydown = disableRefresh; function disableRefresh(evt){ evt = (evt) ? evt : wind ...