springboot通过CompletableFuture开启多线程执行任务

1.直接异步执行一个方法

CompletableFuture.runAsync(() -> {
                        // 业务代码
                    });

2.多线程并行执行

AtomicReference<Map<Integer, String>> map1 = new AtomicReference<>(new HashMap<>());
AtomicReference<Map<Integer, String>> map2 = new AtomicReference<>(new HashMap<>());
AtomicReference<Map<Integer, String>> map3 = new AtomicReference<>(new HashMap<>());

CompletableFuture<Map<Integer, String>> completableFuture1 = completableFuture.supplyAsync(() -> {
    // 业务代码1
    // 执行逻辑处理, map1填充数据
});

CompletableFuture<Map<Integer, String>> completableFuture2 = completableFuture.supplyAsync(() -> {
    // 业务代码2
    // 执行逻辑处理, map2填充数据
});

CompletableFuture<Map<Integer, String>> completableFuture3 = completableFuture.supplyAsync(() -> {
    // 业务代码3
    // 执行逻辑处理, map3填充数据
});

// 此时还没有执行其他线程的方法, 还需要调用执行的方法, 相当于多线程的start()方法
// 开启多线程方法
// allOf表示要等到所有线程执行结束, 主线程才可以继续执行, 相对还有anyOf, 表示里面的几个线程只要任何一个线程有返回就直接继续执行
CompletableFuture.allOf(completableFuture1, completableFuture2, completableFuture3);

CompletableFuture的方法非常多, 还有其他更多的用途可以自行百度

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值