Callable与Future

来源:互联网 发布:自动发微博淘宝客软件 编辑:程序博客网 时间:2024/05/18 22:14

《Executor框架》简单介绍了Executor的概念和用法,在Executor框架中最基本的执行单元是任务,可以使用Runnable表示一个任务。但是Runnable有一个缺点,run()方法返回类型是void, 所以在Executor框架中定义了Callable表示一个任务,可以看做Runnable的加强版。

由Callable定义的任务提交到ExecutorService执行,会返回一个类型为Future的结果,通过Future的get()方法就可以获取任务执行结果,如果任务还没有执行完,则会被阻塞,直到任务执行完毕。下面是Callable和Future接口的定义:

public interface Callable<V> {    V call() throws Exception; //Computes a result, or throws an exception if unable to do so.}

public interface Future<V> {    boolean cancel(boolean mayInterruptIfRunning);    boolean isCancelled();    boolean isDone();    V get() throws InterruptedException, ExecutionException;    V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;}

下面是一个计算Fibonacci数列的一个例子:

public class CallableTest {public static void main(String[] args) throws InterruptedException, ExecutionException {final int nTasks = 5;final int testStart = 20;List<Future<Integer>> results = new ArrayList<Future<Integer>>(nTasks);ExecutorService executor = Executors.newCachedThreadPool();for (int i = 0; i < nTasks; i++){results.add(executor.submit(new Fibonacci(testStart + i))); //1System.out.println("task " + i + " submitted");}for (Future<Integer> fs : results){System.out.println(fs.get()); //2}executor.shutdown(); //3}}class Fibonacci implements Callable<Integer>{private int n;public Fibonacci(int n) {this.n = n;}@Overridepublic Integer call() throws Exception {return calc(n);}private Integer calc(int n) throws Exception {if ( n < 0 )throw new Exception("Illegal argument");if ( n <= 1)return n;elsereturn calc(n-1) + calc(n-2);}}

//1:创建任务并提交,提交后Executor就会启动线程计算。

//2:通过get()获取结果,如果还没有计算完,get()就被阻塞。

//3:完成任务后关闭线程池。




原创粉丝点击