学无先后,达者为师

网站首页 编程语言 正文

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

作者:&165 更新时间: 2024-07-14 编程语言

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的方法非常多, 还有其他更多的用途可以自行百度

原文链接:https://blog.csdn.net/qq_59409315/article/details/140293706

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新