Callable和Future

Future模式

Future接口是Java线程Future模式的实现, 可以来进行异步计算

Callable负责产生结果, Future负责取结果

可以这样解释:

我有一个任务, 提交给了Future, Future则通知Callable替我完成这个任务, 期间我自己可以去做任何想做的事情. 一段时间之后, 就可以从Future那儿取出结果

 

Callable和Future接口

Callable接口

Callable接口类似于Runnable,但是Runnable不会返回结果,而Callable可以返回结果,这个返回值可以被Future拿到,也就是说,Future可以拿到异步执行任务的返回值

/** 
 * Computes a result, or throws an exception if unable to do so. 
 * 
 * @return computed result 
 * @throws Exception if unable to compute a result 
 */  
V call() throws Exception; 

Future接口

Future接口有如下几个方法:

1. 取消任务的执行。参数指定是否立即中断任务执行,或者等等任务结束

boolean cancel(boolean mayInterruptIfRunning)

 

2. 任务是否已经取消,任务正常完成前将其取消,则返回 true

boolean isCancelled() 

 

3. 任务是否已经完成。需要注意的是如果任务正常终止、异常或取消,都将返回true

 

boolean isDone() 

 

4. 等待任务执行结束,然后获得V类型的结果。InterruptedException 线程被中断异常, ExecutionException任务执行异常,如果任务被取消,还会抛出CancellationException

 

V get()

 

5. 同上面的get功能一样,多了设置超时时间。参数timeout指定超时时间,uint指定时间的单位,在枚举类TimeUnit中有相关的定义。如果计算超时,将抛出TimeoutException

 

V get(long timeout, TimeUnit unit) 


Future接口提供方法来检测任务是否被执行完,等待任务执行完获得结果。也可以设置任务执行的超时时间,这个设置超时的方法就是实现Java程序执行超时的关键。

所以,如果需要设定代码执行的最长时间,即超时,可以用Java线程池ExecutorService类配合Future接口来实现。

int result = future.get(5000, TimeUnit.MILLISECONDS);

 

下面演示Callable和Future的基本使用方法:

 1 public class Test {
 2     
 3     public static void main(String[] args) {
 4         ExecutorService threadPool = Executors.newSingleThreadExecutor();
 5         Future<String> future = 
 6             threadPool.submit(
 7                     new Callable<String>(){
 8                         public String call() throws Exception {
 9                             Thread.sleep(2000);
10                             return "shen_smile";
11                         }
12             });
13         System.out.println("等待结果");
14         try {
15             System.out.println("拿到结果 " + future.get());
16         } catch (InterruptedException | ExecutionException e) {
17             // TODO Auto-generated catch block
18             e.printStackTrace();
19         }
20     }
21 }

 本文引用了部分http://blog.csdn.net/vking_wang/article/details/9470499 中的内容

posted on 2016-01-17 21:09  沈小洋  阅读(518)  评论(0编辑  收藏  举报

导航