日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

springboot通過CompletableFuture開啟多線程執(zhí)行任務

作者:&165 更新時間: 2024-07-14 編程語言

1.直接異步執(zhí)行一個方法

CompletableFuture.runAsync(() -> {
                        // 業(yè)務代碼
                    });

2.多線程并行執(zhí)行

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(() -> {
    // 業(yè)務代碼1
    // 執(zhí)行邏輯處理, map1填充數(shù)據(jù)
});

CompletableFuture<Map<Integer, String>> completableFuture2 = completableFuture.supplyAsync(() -> {
    // 業(yè)務代碼2
    // 執(zhí)行邏輯處理, map2填充數(shù)據(jù)
});

CompletableFuture<Map<Integer, String>> completableFuture3 = completableFuture.supplyAsync(() -> {
    // 業(yè)務代碼3
    // 執(zhí)行邏輯處理, map3填充數(shù)據(jù)
});

// 此時還沒有執(zhí)行其他線程的方法, 還需要調(diào)用執(zhí)行的方法, 相當于多線程的start()方法
// 開啟多線程方法
// allOf表示要等到所有線程執(zhí)行結(jié)束, 主線程才可以繼續(xù)執(zhí)行, 相對還有anyOf, 表示里面的幾個線程只要任何一個線程有返回就直接繼續(xù)執(zhí)行
CompletableFuture.allOf(completableFuture1, completableFuture2, completableFuture3);

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

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

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新