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);
        }
相关推荐
TH_14 分钟前
2、前台工程使用代理,请求后台失败
java
川贝枇杷膏cbppg6 分钟前
DmServiceDMSERVER.log是干嘛的
java·服务器·数据库
无敌最俊朗@16 分钟前
Qt 多线程编程: moveToThread 模式讲解
java·开发语言
程序员清风40 分钟前
别卷模型了!上下文工程才是大模型应用的王道!
java·后端·面试
go__Ahead41 分钟前
【Java】ThreadLocal源码解析
java
利剑 -~1 小时前
Spring AI Alibaba 1.1版本
java·人工智能·spring
雨中飘荡的记忆1 小时前
Guava工具库实战
java
while(1){yan}1 小时前
JAVA中如何操作文件
java·开发语言·面试
SuperherRo1 小时前
JAVA攻防-FastJson专题&各版本Gadget链&autoType开关&黑名单&依赖包&本地代码
java·fastjson·1.2.24·1.2.47·1.2.62·1.2.80
爬山算法1 小时前
Netty(5)Netty的ByteBuf是什么?它与Java NIO的ByteBuffer有何不同?
java·开发语言·nio