CompletableFuture 异步调用,获取返回值

复制代码
 ExecutorService executor = new ThreadPoolExecutor(
                8, 16, 60,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(100)
        );

        Random random=new Random(10);
        //模拟查询用户列表
        List<User> list=selectUsers();//需要执行的任务列表

        // 任务列表
        List<CompletableFuture<User>> fList = new ArrayList<>();
        list.forEach(u->{
            CompletableFuture<User> f = CompletableFuture.supplyAsync(//异步执行方法
                    //执行耗时较长的业务代码,这里模拟一下
                    ()->{
                        //执行完成,设置返回结果 设置 coede 和 list
                        u.setAge(random.nextInt(100));
                        u.setName(UUID.randomUUID().toString());
                        return u;
                    },
                    executor
            );
            fList.add(f);
        });


        // 阻塞,等待所有任务执行完成
        CompletableFuture<Void> all= CompletableFuture.allOf(fList.toArray(new CompletableFuture[0]));

        //因为allOf没有返回值,所以需要通过thenApply回调函数获取结果
        CompletableFuture<List<User>> allUser=all.thenApply(v-> fList.stream().map(a-> {
            try {
                return a.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList()));
//        ---------------获取返回值-----------------

        try {
            list=allUser.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
相关推荐
凯芸呢14 分钟前
Java中的数组(续)
java·开发语言·数据结构·算法·青少年编程·排序算法·idea
竹竹零21 分钟前
JacksonUtil--序列化与反序列化
java·开发语言·windows
钱多多_qdd32 分钟前
基础篇:IoC(三):Bean实例化策略InstantiationStrategy
java·spring
float_com34 分钟前
【java基础语法】---- 综合训练
java
Dyan_csdn40 分钟前
springboot系统设计选题3
java·spring boot·后端
sheji34161 小时前
【开题答辩全过程】以 基于Java的旅游网站的设计与开发为例,包含答辩的问题和答案
java·开发语言·旅游
ABdolphin1 小时前
Spring-cloud 主键Eureka
java·云原生·eureka
Aesopcmc1 小时前
Maven打包时指定输出路径、以时间戳命名包名和路径名,结合IDEA以指令脚本方式动态配置输出目录
java·自动化·maven·intellij-idea
蓝-萧2 小时前
springboot系列--自动配置原理
java·后端