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

學無先后,達者為師

網站首頁 編程語言 正文

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

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