zoukankan      html  css  js  c++  java
  • 多线程篇七:通过Callable和Future获取线程池中单个务完成后的结果

    使用场景:如果需要拿到线程的结果,或者在线程完成后做其他操作,可以使用Callable 和 Futrue

    1.定义一个线程池,向线程池中提交单个callable任务

    ExecutorService threadPools=Executors.newSingleThreadExecutor();
            Future<String> future=threadPools.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    Thread.sleep(2000);//模拟任务处理2S
                    return "hello";
                }
                
            });
            System.out.println("等待结果。。。。。");
            try {
                System.out.println("获取到结果:"+future.get());//2S之后任务完成后获取到结果
            } catch (Exception e) {
                e.printStackTrace();
            }

    2.CompletionService 用于提交一组callable任务,并获取每一个任务的结果

    ExecutorService threadPools2=Executors.newFixedThreadPool(10);
            CompletionService<Integer> completetionService=new ExecutorCompletionService<Integer>(threadPools2);
            //提交10个任务
            for(int i=1;i<=10;i++){
                final int seq=i;
                completetionService.submit(new Callable<Integer>(){
                    @Override
                    public Integer call() throws Exception {
                        Thread.sleep(new Random().nextInt(5000));
                        return seq;
                    }
                    
                });
            }
            
            for(int i=1;i<=10;i++){
                  Future<Integer> futures;
                try {
                    futures = completetionService.take();
                    System.out.println("拿到任务结果:"+futures.get());//在任务完成后拿到结果,哪个任务先完成,则先拿到结果
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
  • 相关阅读:
    【转】Exchange Server 的防火墙开放端口
    【转】AD常用端口
    centos6安装python3
    CMD下的netstat命令
    CMD定时倒数
    【转】netstat 的10个基本用法
    不联网如何PING通WIN主机和VMWARE(懵懂版,不含原理)
    【转载】Putty出现 Network error:Software caused connection abort
    MFC Unicode 字符集下格式转换
    MFC嵌套OpenCV窗口并显示图片
  • 原文地址:https://www.cnblogs.com/brant/p/6028544.html
Copyright © 2011-2022 走看看