首页 > 其他 > 详细

Callable和Future

时间:2015-03-18 06:35:50      阅读:240      评论:0      收藏:0      [点我收藏+]

// 创建一个线程
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<String> future = executorService.submit(new Callable<String>() {
            @Override
            public String call() throws InterruptedException {
                Thread.sleep(1000);
                return "success";
            }
        });
        System.out.println(future.get());
        //创建十个线程
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(threadPool);
        for (int i = 0; i < 10; i++) {
            final int sq = i;
            completionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    Thread.sleep(new Random().nextInt(1000));
                    return sq;
                }
            });
        }
        for (int i = 0; i < 10; i++) {
            System.out.println(completionService.take().get());
        }

Callable 和Runable最大的区别就是Callable是有返回值的,用线程池ExecutorService创建线程的时候,不妨把这个线程池交给ExecutorCompletionService类来处理。可以将返回值用list来封装。

Callable和Future

原文:http://7981774.blog.51cto.com/7971774/1621606

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