首页 > 其他 > 详细

Callable和Future

时间:2014-11-01 19:16:37      阅读:145      评论:0      收藏:0      [点我收藏+]

Callable方法比Runnable强大一些在于它被线程执行后有返回值,该返回值可以被Future拿到。

用法:

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

    public Integer call() throws Exception {

        //do sth    

    }

};


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

new Thread(future).start();


String result = future.get();//获取返回结果


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

ExecutorService threadPool = Executors.newSingleThreadExecutor();

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

    public Integer call() throws Exception {

        //do sth

    }

});

future.get();


执行多个待返回值得任务,并取得多个返回值:

ExecutorService threadPool = Executors.newCachedThreadPool();

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

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

    final int taskID = i;

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

        public Integer call() throws Exception{

            return taskID;

        }

    };

}


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

    cs.take().get

}

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

Callable和Future

原文:http://6169621.blog.51cto.com/6159621/1570757

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!