十:Callable和Future

来源:互联网 发布:期货交易行情软件 编辑:程序博客网 时间:2024/04/20 07:11

前记

上一篇温习的是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
原创粉丝点击