码迷,mamicode.com
首页 > 编程语言 > 详细

【Java线程】Callable和Future

时间:2015-05-18 16:57:37      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

Future模式

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

Future模式可以这样来描述:

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

就相当于下了一张订货单,一段时间后可以拿着提订单来提货,这期间可以干别的任何事情。其中Future接口就是订货单,真正处理订单的是Executor类,它根据Future接口的要求来生产产品。


Callable和Future接口

Callable接口

Callable和Future一个产生结果,一个拿到结果。

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

  •  V call()

  1. /** 

  2.  * Computes a result, or throws an exception if unable to do so. 

  3.  * 

  4.  * @return computed result 

  5.  * @throws Exception if unable to compute a result 

  6.  */  

  7. V call() throws Exception;  



Future接口

Future 表示异步计算的结果。Future接口中有如下方法:

  •     boolean cancel(boolean mayInterruptIfRunning)

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

  •     boolean isCancelled() 

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

  •     boolean isDone()

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

  •     V get()

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

  •     V get(long timeout, TimeUnit unit) 

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

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

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

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



Future实现类:SwingWorker

SwingWorker的用法

http://blog.csdn.net/vking_wang/article/details/8994882


Future实现类:FutureTask

Future的实现类有java.util.concurrent.FutureTask<V>即 javax.swing.SwingWorker<T,V>。通常使用FutureTask来处理我们的任务。

FutureTask类同时又实现了Runnable接口,所以可以直接提交给Thread、Executor执行。


  1. public class CallableAndFuture {    

  2.     public static void main(String[] args) {    

  3.         Callable<Integer> callable = new Callable<Integer>() {    

  4.             public Integer call() throws Exception {    

  5.                 return new Random().nextInt(100);    

  6.             }    

  7.         };   

  8.   

  9.         FutureTask<Integer> future = new FutureTask<Integer>(callable);    

  10.         new Thread(future).start();    

  11.   

  12.         try {    

  13.             Thread.sleep(5000);// 可能做一些事情    

  14.   

  15.             int result = future.get());    

  16.   

  17.         } catch (InterruptedException e) {    

  18.             e.printStackTrace();    

  19.         } catch (ExecutionException e) {    

  20.             e.printStackTrace();    

  21.         }    

  22.     }    

  23. }    


通过ExecutorService的submit方法执行Callable,并返回Future

使用ExecutorService


  1. public class CallableAndFuture {    

  2.     public static void main(String[] args) {   

  3.   

  4.         //ExecutorService.submit()  

  5.         ExecutorService threadPool = Executors.newSingleThreadExecutor();    

  6.         Future<Integer> future = threadPool.submit(new Callable<Integer>() {    

  7.             public Integer call() throws Exception {    

  8.                 return new Random().nextInt(100);    

  9.             }    

  10.         });   

  11.   

  12.         try {    

  13.             Thread.sleep(5000);// 可能做一些事情    

  14.   

  15.             int result = future.get()); //Future.get()  

  16.   

  17.         } catch (InterruptedException e) {    

  18.             e.printStackTrace();    

  19.         } catch (ExecutionException e) {    

  20.             e.printStackTrace();    

  21.         }    

  22.     }    

  23. }    


如果要执行多个带返回值的任务,并取得多个返回值,可用CompletionService:

CompletionService相当于Executor加上BlockingQueue,使用场景为当子线程并发了一系列的任务以后,主线程需要实时地取回子线程任务的返回值并同时顺序地处理这些返回值,谁先返回就先处理谁。


  1. public class CallableAndFuture {    

  2.     public static void main(String[] args) {    

  3.         ExecutorService threadPool = Executors.newCachedThreadPool();    

  4.         CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);    

  5.         for(int i = 1; i < 5; i++) {    

  6.             final int taskID = i;    

  7.             //CompletionService.submit()  

  8.             cs.submit(new Callable<Integer>() {    

  9.                 public Integer call() throws Exception {    

  10.                     return taskID;    

  11.                 }    

  12.             });    

  13.         }    

  14.         // 可能做一些事情    

  15.         for(int i = 1; i < 5; i++) {    

  16.             try {    

  17.                 int result = cs.take().get());  //CompletionService.take()返回Future  

  18.             } catch (InterruptedException e) {    

  19.                 e.printStackTrace();    

  20.             } catch (ExecutionException e) {    

  21.                 e.printStackTrace();    

  22.             }    

  23.         }    

  24.     }    

  25. }          


或者不使用CompletionService:先创建一个装Future类型的集合,用Executor提交的任务返回值添加到集合中,最后便利集合取出数据。


区别:

Future集合方法,submit的task不一定是按照加入自己维护的list顺序完成的。从list中遍历的每个Future对象并不一定处于完成状态,这时调用get()方法就会被阻塞住,如果系统是设计成每个线程完成后就能根据其结果继续做后面的事,这样对于处于list后面的但是先完成的线程就会增加了额外的等待时间。

而CompletionService的实现是维护一个保存Future对象的BlockingQueue。只有当这个Future对象状态是结束的时候,才会加入到这个Queue中,take()方法其实就是Producer-Consumer中的Consumer。它会从Queue中取出Future对象,如果Queue是空的,就会阻塞在那里,直到有完成的Future对象加入到Queue中。

所以,先完成的必定先被取出。这样就减少了不必要的等待时间。


【Java线程】Callable和Future

标签:

原文地址:http://my.oschina.net/u/2329222/blog/416258

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!