本篇说明的是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的更多相关文章

  1. Java Callable接口与Future接口的两种使用方式

    Java Callable.Future的两种使用方式Callable+Futurepublic class Test { public static void main(String[] args) ...

  2. Callable接口、Runable接口、Future接口

    1. Callable与Runable区别 Java从发布的第一个版本开始就可以很方便地编写多线程的应用程序,并在设计中引入异步处理.Thread类.Runnable接口和Java内存管理模型使得多线 ...

  3. Java Callable接口、Runable接口、Future接口

    1. Callable与Runable区别 Java从发布的第一个版本开始就可以很方便地编写多线程的应用程序,并在设计中引入异步处理.Thread类.Runnable接口和Java内存管理模型使得多线 ...

  4. Future接口和Callable接口以及FeatureTask详解

    类继承关系 Callable接口 @FunctionalInterface public interface Callable<V> { V call() throws Exception ...

  5. 实现Callable接口,并与Future结合使用

    实现步骤: 创建 Callable 接口的实现类,并实现 call() 方法,该 call() 方法将作为线程执行体,并且有返回值. 创建 Callable 实现类的实例,使用 FutureTask ...

  6. 线程池的应用及Callable接口的使用

    public interface Executor { /** * Executes the given command at some time in the future.  The comman ...

  7. [改善Java代码]异步运算考虑使用Callable接口

    多线程有两种实现方式: 一种是实现Runnable接口,另一种是继承Thread类,这两种方式都有缺点,run方法没有返回值,不能抛出异常(这两个缺点归根到底是Runable接口的缺陷,Thread也 ...

  8. 多线程——实现Callable接口

    前两篇博客(多线程--继承Thread类.多线程--实现Runnable接口 )介绍了java使用线程的两种方法.这篇博客继续介绍第三种方法--实现Callable接口. 先说一下Runnable和C ...

  9. Java多线程之Callable接口的实现

    Callable 和 Future接口  Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务. Callable和Runn ...

随机推荐

  1. anu - reactIE

    import { options } from "./util"; import { Children } from "./Children"; import ...

  2. Jmeter实现MySQL的增删改查操作

    环境: JDBC驱动:mysql-connector-java-5.1.7-bin Jmeter:Jmeter3.0 1.导入JDBC驱动:测试计划-->浏览-->选择mysql-conn ...

  3. Cookie注入实战(非SQL注入)

    cookie注入原理其实很简单,就是利用了session机制中的特性,只能说是特性,不能算是漏洞. 这里简单的说下原理,session的机制就相当于你有一张蛋糕店的会员卡,这张会员卡就是你浏览器中的c ...

  4. NBUT 1220 SPY 2010辽宁省赛

    Time limit  1000 ms Memory limit  131072 kB The National Intelligence Council of X Nation receives a ...

  5. 【转】重装win7后,所有USB接口无法使用(鼠标、键盘、U盘)

    转自:https://blog.csdn.net/u010887744/article/details/45270245 今天给一朋友重装系统,华硕FX50J,修改BIOS重装了win7,结果所有US ...

  6. SIM800C SIM卡唯一标识符ICCID

    /******************************************************************************* * SIM800C SIM卡唯一标识符 ...

  7. TJU Problem 2520 Quicksum

    注意: for (int i = 1; i <= aaa.length(); i++) 其中是“ i <= ",注意等号. 原题: 2520.   Quicksum Time L ...

  8. 计算n^k的开头三位和末尾三位(fmod(double x,double y)函数的引入)

    C 库函数 double fmod(double x, double y) 返回 x 除以 y 的余数. 所以fmod(x,1)得到的就是小数部分的值(如fmod(3.35,1)==0.35) htt ...

  9. 关联容器map(红黑树,key/value),以及所有的STL容器详解

    字符串或串(String)是由数字.字母.下划线组成的一串字符.一般记为 s=“a1a2···an”(n>=0).它是编程语言中表示文本的数据类型.在程序设计中,字符串(string)为符号或数 ...

  10. smarty学习——变量调节器(过滤器)

    变量调节器用于变量,自定义函数和字符串. 请使用 | 符号和调节器名称应用调节器.变量调节器由赋予的参数值决定其行为.参数由:符号分开. 比如进行大写转换的: upper demo: <br&g ...