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

Callable和Future实现多线程

时间:2016-07-06 18:42:22      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:callable和future实现多线程


Callable和Future实现多线程


  

      Future取得的结构类型和Callable返回的结果类型必须一致。

      Callable要采用ExecutorServicesubmit方法提交,返回的future对象可以取消任务


        1.提交任务,得到任务的返回结果举例

        ExecutorService threadPool = Executors.newSingleThreadExecutor();

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

        @Override

        public String call() throws Exception {

        // TODO Auto-generated method stub

        return "hello";

        }

        });

    future.get();

    2.CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的

      Future对象。就是一件事让多个线程去执行,谁先执行完,就取得谁的结果。例子如下:

      ExecutorService threadPool2 = Executors.newFixedThreadPool(10);

      CompletionService<String> completionService = new ExecutorCompletionService<String>

                                                        (threadPool2);

        for (int i = 0; i < 10; i++) {

        completionService.submit(new Callable<String>() {

        @Override

        public String call() throws Exception {

        return "hello";

        }

        });

        }

    

        for (int i = 0; i < 10; i++) {

        completionService.take().get();

        }

      





本文出自 “德泽无忧” 博客,谢绝转载!

Callable和Future实现多线程

标签:callable和future实现多线程

原文地址:http://dezewuyou.blog.51cto.com/2628602/1803515

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