Future接口

在Java中,如果需要设定代码执行的最长时间,即超时,可以用Java线程池ExecutorService类配合Future接口来实现。 Future接口是Java标准API的一部分,在java.util.concurrent包中。Future接口是Java线程Future模式的实现,可以来进行异步计算。

Future模式可以这样来描述:我有一个任务,提交给了Future,Future替我完成这个任务。期间我自己可以去做任何想做的事情。一段时间之后,我就便可以从Future那儿取出结果。就相当于下了一张订货单,一段时间后可以拿着提订单来提货,这期间可以干别的任何事情。其中Future 接口就是订货单,真正处理订单的是Executor类,它根据Future接口的要求来生产产品。

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

Future接口是一个泛型接口,严格的格式应该是Future<V>,其中V代表了Future执行的任务返回值的类型。 Future接口的方法介绍如下:

  • boolean cancel (boolean mayInterruptIfRunning) 取消任务的执行。参数指定是否立即中断任务执行,或者等等任务结束
  • boolean isCancelled () 任务是否已经取消,任务正常完成前将其取消,则返回 true
  • boolean isDone () 任务是否已经完成。需要注意的是如果任务正常终止、异常或取消,都将返回true
  • get () throws InterruptedException, ExecutionException  等待任务执行结束,然后获得V类型的结果。InterruptedException 线程被中断异常, ExecutionException任务执行异常,如果任务被取消,还会抛出CancellationException
  • get (long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException 同上面的get功能一样,多了设置超时时间。参数timeout指定超时时间,uint指定时间的单位,在枚举类TimeUnit中有相关的定义。如果计算超时,将抛出TimeoutException

Future的实现类有java.util.concurrent.FutureTask<V>即 javax.swing.SwingWorker<T,V>。通常使用FutureTask来处理我们的任务。FutureTask类同时又实现了Runnable接口,所以可以直接提交给Executor执行。使用FutureTask实现超时执行的代码如下:

Java代码  复制代码
  1. ExecutorService executor = Executors.newSingleThreadExecutor();   
  2. FutureTask<String> future =   
  3.        new FutureTask<String>(new Callable<String>() {//使用Callable接口作为构造参数   
  4.          public String call() {   
  5.            //真正的任务在这里执行,这里的返回值类型为String,可以为任意类型   
  6.        }});   
  7. executor.execute(future);   
  8. //在这里可以做别的任何事情   
  9. try {   
  10.     result = future.get(5000, TimeUnit.MILLISECONDS); //取得结果,同时设置超时执行时间为5秒。同样可以用future.get(),不设置执行超时时间取得结果   
  11. catch (InterruptedException e) {   
  12.     futureTask.cancel(true);   
  13. catch (ExecutionException e) {   
  14.     futureTask.cancel(true);   
  15. catch (TimeoutException e) {   
  16.     futureTask.cancel(true);   
  17. finally {   
  18.     executor.shutdown();   
  19. }  

 

不直接构造Future对象,也可以使用ExecutorService.submit方法来获得Future对象,submit方法即支持以 Callable接口类型,也支持Runnable接口作为参数,具有很大的灵活性。使用示例如下:

Java代码  复制代码
  1. ExecutorService executor = Executors.newSingleThreadExecutor();   
  2. FutureTask<String> future = executor.submit(   
  3.    new Callable<String>() {//使用Callable接口作为构造参数   
  4.        public String call() {   
  5.       //真正的任务在这里执行,这里的返回值类型为String,可以为任意类型   
  6.    }});   
  7. //在这里可以做别的任何事情   
  8. //同上面取得结果的代码  


        Callable接口类似于Runnable,从名字就可以看出来了,但是Runnable不会返回结果,并且无法抛出返回结果的异常,而Callable功能更强大一些,被线程执行后,可以返回值,这个返回值可以被Future拿到,也就是说,Future可以拿到异步执行任务的返回值,下面来看一个简单的例子:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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.         FutureTask<Integer> future = new FutureTask<Integer>(callable);  
  9.         new Thread(future).start();  
  10.         try {  
  11.             Thread.sleep(5000);// 可能做一些事情  
  12.             System.out.println(future.get());  
  13.         } catch (InterruptedException e) {  
  14.             e.printStackTrace();  
  15.         } catch (ExecutionException e) {  
  16.             e.printStackTrace();  
  17.         }  
  18.     }  
  19. }  
        FutureTask实现了两个接口,Runnable和Future,所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值,那么这个组合的使用有什么好处呢?假设有一个很耗时的返回值需要计算,并且这个返回值不是立刻需要的话,那么就可以使用这个组合,用另一个线程去计算返回值,而当前线程在使用这个返回值之前可以做其它的操作,等到需要这个返回值时,再通过Future得到,岂不美哉!这里有一个Future模式的介绍: http://openhome.cc/Gossip/DesignPattern/FuturePattern.htm

        下面来看另一种方式使用Callable和Future,通过ExecutorService的submit方法执行Callable,并返回Future,代码如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class CallableAndFuture {  
  2.     public static void main(String[] args) {  
  3.         ExecutorService threadPool = Executors.newSingleThreadExecutor();  
  4.         Future<Integer> future = threadPool.submit(new Callable<Integer>() {  
  5.             public Integer call() throws Exception {  
  6.                 return new Random().nextInt(100);  
  7.             }  
  8.         });  
  9.         try {  
  10.             Thread.sleep(5000);// 可能做一些事情  
  11.             System.out.println(future.get());  
  12.         } catch (InterruptedException e) {  
  13.             e.printStackTrace();  
  14.         } catch (ExecutionException e) {  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
  18. }  
        代码是不是简化了很多,ExecutorService继承自Executor,它的目的是为我们管理Thread对象,从而简化并发编程,Executor使我们无需显示的去管理线程的生命周期,是JDK 5之后启动任务的首选方式。

        执行多个带返回值的任务,并取得多个返回值,代码如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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.             cs.submit(new Callable<Integer>() {  
  8.                 public Integer call() throws Exception {  
  9.                     return taskID;  
  10.                 }  
  11.             });  
  12.         }  
  13.         // 可能做一些事情  
  14.         for(int i = 1; i < 5; i++) {  
  15.             try {  
  16.                 System.out.println(cs.take().get());  
  17.             } catch (InterruptedException e) {  
  18.                 e.printStackTrace();  
  19.             } catch (ExecutionException e) {  
  20.                 e.printStackTrace();  
  21.             }  
  22.         }  
  23.     }  
  24. }        

        其实也可以不使用CompletionService,可以先创建一个装Future类型的集合,用Executor提交的任务返回值添加到集合中,最后遍历集合取出数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值