十:Callable和Future

前记

上一篇温习的是java5中的线程池的知识,这次是来温习带返回值的Callable和Future知识。

场景及代码

由于FutureTask实现了两个接口,Runnable和Future,所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值,那么这个组合的使用有什么好处呢?假设有一个很耗时的返回值需要计算,并且这个返回值不是立刻需要的话,那么就可以使用这个组合,用另一个线程去计算返回值,而当前线程在使用这个返回值之前可以做其它的操作,等到需要这个返回值时,再通过Future得到,岂不美哉!这里有一个Future模式的介绍:http://openhome.cc/Gossip/DesignPattern/FuturePattern.htm
第一种应用

一直等待结果,等待的过程中程序也无法进行其他操作,跟直接去调用一个方法来获取返回结果感觉是一样的效果。

public class CallableAndFuture {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<String> future = threadPool.submit(
                new Callable<String>() {
                    public String call() throws Exception {
                        Thread.sleep(2000);
                        return "test";
                    };
                }
        );
        System.out.println("等待结果......");
        try {
            System.out.println("结果---->"+future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

第二种应用
CompletionService一次提交一组Callable任务,它take方法返回已经完成的一个Callable任务对应的Future对象。
例子:好比是一个渔夫在大海中撒网,撒了很多区域等待收网,具体收网的顺序则是哪个网进鱼了则先收哪个。

public class CallableAndFuture {

        ExecutorService threadPoolTest = Executors.newFixedThreadPool(10);
        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPoolTest);
        //提交10个任务
        for (int i = 0; i < 10; i++) {
            final int index = i;
            completionService.submit(new Callable<Integer>() {

                @Override
                public Integer call() throws Exception {
                    Thread.sleep(new Random().nextInt(5000));
                    return index;
                }

            });
        }
        for (int i = 0; i < 10; i++) {
            System.out.println(completionService.take().get());
        }

    }

}

以上…..

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值