频道栏目
首页 > 资讯 > 其他 > 正文

Callable和Future的应用详情

17-12-11        来源:[db:作者]  
收藏   我要投稿
Callable和Future这两个组合一起可以实现:
程序启动一个线程,然后线程运行完以后,它可以给我们返回结果
public class CallableAndFuture {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future future =   //Future取得的结果类型和Callable返回的结果类型必须一致,这是通过泛型来实现的
        threadPool.submit(new Callable() {//Callable要采用ExecutorSevice的submit方法提交,返回的future对象可以取消任务;这里如果使用execute(Runnable command)方法,则没有返回值
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                return "hello";
            }
        });
        System.out.println("等待结果");
        try {
           System.out.println("拿到结果:"+future.get());

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }



}

这里写图片描述

public class CallableAndFuture {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future future =
        threadPool.submit(new Callable() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                return "hello";
            }
        });
        System.out.println("等待结果");
        try {

                System.out.println("拿到结果:"+future.get(1, TimeUnit.SECONDS));//没有结果就抛异常


        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }


    }



}

这里写图片描述

CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象
好比我同时种了几块地的麦子,然后就等待收割。收割时,则是哪块先成熟了,则先去收割哪块麦子
  ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
        CompletionService completionService = new ExecutorCompletionService(threadPool2);
        for(int i = 1 ;i<=10;i++) {
            final int seq = i ;
            completionService.submit(new Callable() {
                @Override
                public Integer call() throws Exception {
                            Thread.sleep(2000);
                    return seq;
                }
            });
        }
        for(int i = 0 ;i<=10;i++){
            try {
                System.out.println(completionService.take().get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

        }

这里写图片描述

相关TAG标签
上一篇:算法复杂度“编程题”
下一篇:c#是怎样抓取html网页数据的?(代码实例)
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站