国产精品电影_久久视频免费_欧美日韩国产激情_成年人视频免费在线播放_日本久久亚洲电影_久久都是精品_66av99_九色精品美女在线_蜜臀a∨国产成人精品_冲田杏梨av在线_欧美精品在线一区二区三区_麻豆mv在线看

30+個 CompletableFuture 高頻場景案例,讓你的系統性能飆升300%

開發 前端
CompletableFuture?位于 JUC 包中,用于表示異步計算的未來結果。與傳統的Future不同(傳統Future僅允許在計算完成后獲取結果),CompletableFuture提供了豐富的API來構建復雜的異步操作流水線。它支持多種操作,例如合并多個Future、處理異常以及非阻塞地執行任務等。

環境:SpringBoot3.4.2

1. 簡介

什么是CompletableFuture?

CompletableFuture 位于 JUC 包中,用于表示異步計算的未來結果。與傳統的Future不同(傳統Future僅允許在計算完成后獲取結果),CompletableFuture提供了豐富的API來構建復雜的異步操作流水線。它支持多種操作,例如合并多個Future、處理異常以及非阻塞地執行任務等。

CompletableFuture的核心特性:

  • 非阻塞:可以在不阻塞主線程的情況下執行任務
  • 任務鏈式調用:可以將多個異步任務串聯在一起
  • 異常處理:提供了更優雅的異常處理方法
  • 合并Future:可以將多個Future合并為一個Future

何時使用:

  • 異步操作:當需要執行可以獨立運行而無需相互等待的任務時
  • I/O操作:非常適合網絡調用、文件I/O或數據庫查詢等存在延遲的場景
  • 復雜工作流:當有多個相互依賴或獨立的任務需要按特定順序執行時

為什么使用:

  • 提升性能:通過利用非阻塞操作,可以更好地利用系統資源,提高應用程序的響應能力
  • 簡化代碼:與傳統的回調方式相比,它有助于更優雅地管理異步代碼
  • 優雅的異常處理:提供了內置的機制來處理異步處理過程中可能出現的異常

接下來,我們將詳細介紹使用CompletableFuture的50個常見使用場景。

2.實戰案例

2.1 簡單異步任務

CompletableFuture.runAsync(() -> {
  System.out.println("異步線程執行任務");
});

2.2 異步任務返回結果

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 42) ;

2.3 使用 thenApply 鏈式任務

CompletableFuture<Integer> future = CompletableFuture
        .supplyAsync(() -> 10)
        .thenApply(result -> result * 2);

2.4 使用thenAccept處理結果

CompletableFuture.supplyAsync(() -> 10)
  .thenAccept

2.5 任務完成而不消費結果(thenRun)

CompletableFuture.supplyAsync(() -> 10)
      .thenRun(() -> System.out.println("任務執行完成.")) ;

2.6 使用 thenCombine 組合兩個Future

CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(() -> 20);
CompletableFuture<Integer> ret = f1.thenCombine(f2, Integer::sum);
ret.thenAccept(result -> System.out.println("合并后的結果: " + result));

2.7 用 allOf 等待所有Future

CompletableFuture<Void> allFutures = CompletableFuture.allOf(
    CompletableFuture.supplyAsync(() -> "Task 1"),
    CompletableFuture.supplyAsync(() -> "Task 2")
);
// 主線程將被阻塞
allFutures.join();

2.8 使用 anyOf 等待任何一個完成

CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(
  CompletableFuture.supplyAsync(() -> {
    try {TimeUnit.SECONDS.sleep(3) ;} catch (InterruptedException e) {}
    return "Task 1" ;
  }),
  CompletableFuture.supplyAsync(() -> {
    try {TimeUnit.SECONDS.sleep(1) ;} catch (InterruptedException e) {}
    return "Task 2" ;
  })
);
anyFuture.thenAccept(result -> System.out.println("第一個完成的: " + result)) ;

上面代碼輸出:Task 2。

2.9 使用exceptionally處理異常

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
  System.err.println(1 / 0) ;
  return 666 ;
}).exceptionally(ex -> {
  System.out.println("Exception: " + ex.getMessage());
  return -1 ;
});
System.err.println(future.get()) ;

輸出:-1。

2.10 使用 handle 同時處理結果和異常

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
  System.err.println(1 / 0) ;
  return 666 ;
}).handle((result, ex) -> {
  if (ex != null) {
    return 0;
  }
  return result;
});

當supplyAsync方法執行時拋出異常則通過handle捕獲并返回默認值0,否則返回結果666。

2.11 在另一個任務完成后運行任務(thenCompose)

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 10)
    .thenCompose(result -> CompletableFuture.supplyAsync(() -> result * 2)) ;

該代碼通過thenCompose鏈式組合兩個異步任務,將前一個結果(10)乘以2,最終得到CompletableFuture<Integer>(值為20)。

2.12 異步HTTP請求

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("http://localhost:8080/users/1"))
    .build();
CompletableFuture<HttpResponse<String>> future = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
future.thenAccept(respons

使用HttpClient異步發送HTTP請求,通過CompletableFuture處理響應字符串,非阻塞獲取結果。

輸出結果

{"id":1,"name":"姓名 - 1","age":72}

2.13 指定運行任務的線程池

ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2)) ;
CompletableFuture.runAsync(() -> {
  System.out.printf("%s - 執行任務") ;
}, executor);

2.14 鏈式執行多個Future

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 10)
    .thenApply(result -> result + 5)
    .thenApply(result -> result * 2);
future.thenAccept(result -> System.out.println("最終結果: " + result)) ;

前一個任務執行的結果作為下一個任務的入參。

2.15 手動完成Future

CompletableFuture<Integer> future = new CompletableFuture<>();
future.complete(10);
future.thenAccept(result -> System.out.println("最終結果: " + result));
future.join() ;

2.16 設定任務執行超時時間

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
  try { Thread.sleep(2000); } catch (InterruptedException e) { }
  return 10;
});
future.orTimeout(1, TimeUnit.SECONDS).exceptionally(ex -> {
  System.out.println("任務執行超時...");
  return null ;
});
future.join() ;

運行結果

圖片

2.17 超時任務返回默認值

CompletableFuture.supplyAsync(() -> {
  try { Thread.sleep(2000); } catch (InterruptedException e) { }
  return 10;
})
.completeOnTimeout(666, 1, TimeUnit.SECONDS)
.thenAccept(result -> System.out.println("Result: " + result));

運行結果

Result:666

2.18 使用Stream API組合多個Future

List<CompletableFuture<Integer>> futures = List.of(
  CompletableFuture.supplyAsync(() -> 10),
  CompletableFuture.supplyAsync(() -> 20),
  CompletableFuture.supplyAsync(() -> 30)
);
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(
  futures.toArray(new CompletableFuture[0])
);
combinedFuture.thenAccept(result -> {
  List<Integer> results = futures.stream()
      .map(CompletableFuture::join)
      .toList() ;


  System.out.println(results) ;
}).join();

運行結果

[10, 20, 30]

2.19 指定延遲完成任務

CompletableFuture<Integer> future = new CompletableFuture<>();
Executors.newSingleThreadScheduledExecutor().schedule(() -> {
  future.complete(42) ;
}, 2, TimeUnit.SECONDS) ;
future.thenAccept(System.out::println).join() ;

延遲2s后輸出結果42。

2.20 使用 thenAcceptBoth 組合兩個結果

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 20);
future1.thenAcceptBoth(future2, (res1, res2) -> {
    System.out.println("合并結果: " + (res1 + res2));
}).join() ;

2.21 acceptEither優先處理先完成的異步任務結果

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
  try {TimeUnit.SECONDS.sleep(3) ;} catch (InterruptedException e) {e.printStackTrace();}
  return 10 ;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
  try {TimeUnit.SECONDS.sleep(2) ;} catch (InterruptedException e) {e.printStackTrace();}
  return 20 ;
});
future1.acceptEither(future2, result -> {
  System.out.println("結果: " + result);
}).join() ;

輸出結果:20。

acceptEither 取 future1 和 future2 中先完成的結果,非阻塞處理(輸出先到達的值,10 或 20)。

2.22 取消任務執行

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
  try { Thread.sleep(2000); } catch (InterruptedException e) { }
  return 10;
});
future.cancel(true) ;

2.23 使用 whenComplete 完成最終任務

CompletableFuture.supplyAsync(() -> 10)
  .whenComplete((result, ex) -> {
      System.out.println("Final result: " + result);
  }).join();

2.24 處理流式Future

List<CompletableFuture<Integer>> futures = List.of(
  CompletableFuture.supplyAsync(() -> {
    try { Thread.sleep(2000); } catch (InterruptedException e) { }
    return 1 ;
  }),
  CompletableFuture.supplyAsync(() -> {
    try { Thread.sleep(1000); } catch (InterruptedException e) { }
    return 2 ;
  }),
  CompletableFuture.supplyAsync(() -> {
    try { Thread.sleep(3000); } catch (InterruptedException e) { }
    return 3 ;
  })
);
futures.forEach(future -> future.thenAccept(result -> System.out.println("Result: " + result))) ;

輸出結果:

Result: 2
Result: 1
Result: 3

2.25 使用 completeExceptionally 進行異常處理

CompletableFuture<Integer> future = new CompletableFuture<>();
future.completeExceptionally(new RuntimeException("任務執行錯誤"));
future.exceptionally(ex -> {
  System.out.println("Exception: " + ex.getMessage());
  return 0;
});

2.26 使用 thenComposeAsync 進行順序處理

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5)
    .thenComposeAsync(result -> CompletableFuture.supplyAsync(() -> result * 2));
future.thenAccept(result ->

thenComposeAsync:異步轉換結果并鏈式執行后續任務,非阻塞串聯異步邏輯。

2.27 使用 thenCombineAsync 組合任務

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 20);


CompletableFuture<Integer> combinedFuture = future1.thenCombineAsync(future2, Integer::sum);
combinedFuture.thenAccept(r

2.28 阻塞式等待直至完成

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 42);
Integer result = future.get();  // 阻塞直到任務執行完成
System.out.println("結果: " + result);

2.29 合并不同類型的Future

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Result");
CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (num, str) -> num + " " + str);
combinedFuture.then

2.30 使用 thenCombine 和 thenCompose 組合結果

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 20);
CompletableFuture<Integer> finalFuture = future1.thenCombine(future2, Integer::sum)
        .thenCompose(result -> CompletableFuture.supplyAsync(() -> result * 2));
finalFuture.thenAccept(r

2.31 使用 handleAsync 處理異常

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
  System.err.println(1 / 0) ;
  return 888 ;
}).handleAsync((result, ex) -> {
  if (ex != null) {
    System.out.println("Handled exception");
    return 0;
  }
  return result;
});

2.32 等待多個Future(帶超時)

List<CompletableFuture<Integer>> futures = List.of(
  CompletableFuture.supplyAsync(() -> 10),
  CompletableFuture.supplyAsync(() -> 20)
);
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
    .orTimeout(1, TimeUnit.SECONDS);
combinedFuture.thenRun(() -> System.o


責任編輯:武曉燕 來源: Springboot全家桶實戰案例
相關推薦

2025-03-17 03:00:00

C#性能并行處理

2015-11-06 14:40:41

網速wifi

2023-11-22 07:33:58

Redis數據庫

2025-11-26 02:25:00

2019-01-04 13:30:58

系統 優化 數據

2022-06-26 20:37:17

系統性能場景

2024-09-27 19:39:27

2025-04-07 08:50:00

C#代碼編程

2010-04-23 11:44:34

Aix系統

2009-09-29 10:39:04

Linuxlinux系統性能檢測

2011-09-06 13:36:41

Vista

2020-04-26 15:38:28

Docker容器

2023-10-10 16:20:38

JavaScript代碼技巧

2010-04-30 15:53:45

Oracle系統性能

2025-03-31 00:45:00

2011-03-10 14:40:52

2017-08-11 19:13:01

LinuxNmon系統監控工具

2019-05-22 10:57:15

工具微服務架構

2024-12-09 15:00:00

C++20代碼標記

2019-06-06 08:48:14

代碼函數編程語言
點贊
收藏

51CTO技術棧公眾號

在线观看国产麻豆| 免费涩涩18网站入口| 国产精区一区二区| 日韩免费在线观看| 蜜桃专区在线| 国产精品久久久久久久久快鸭| 国产在线视频综合| 亚洲欧美日本国产专区一区| 成人网在线免费看| 免费av一区| 韩国v欧美v日本v亚洲| 国产成人亚洲一区二区三区| 欧美日本在线播放| 第一页在线观看| 色哟哟欧美精品| 在线视频观看你懂的| 亚洲欧美偷拍另类a∨色屁股| 国产亚洲天堂网| 9色porny自拍视频一区二区| 奇米777四色影视在线看| 欧美bbbbb| 日韩精品一区二区三区四区五区| 精品成人国产| 精品国产一区二区三区四区vr| 2023国产精品久久久精品双| 国产精品色午夜在线观看| 中国av一区| 午夜免费久久久久| 欧美午夜18电影| 欧美自拍视频在线观看| 国产精品美女久久久久久不卡| 欧美亚洲另类视频| 成人国产精品一级毛片视频| 国产精品日韩欧美综合| 日韩中文一区二区| 97人人模人人爽人人喊38tv| 久久久噜噜噜久久| 97成人资源| 中文字幕精品国产| 日韩免费成人| 26uuu日韩精品一区二区| 国产真实有声精品录音| 国产精品美女免费视频| 亚洲国产一区二区三区在线播放| 91九色极品视频| 日韩经典一区二区| 国产91沈先生在线播放| 中文av字幕一区| 久久精品色图| 日韩精品极品在线观看播放免费视频| 福利视频一区| 欧亚精品中文字幕| 伊人久久大香线蕉综合热线| 日韩视频在线免费播放| 国产亚洲一区字幕| 深夜影院在线观看| 这里只有精品视频在线观看| 午夜精品久久久久久久久久蜜桃| 欧美国产日韩在线| 欧美一区网站| 永久久久久久| 亚洲欧美在线视频观看| 一区二区三区视频网站| 日韩高清a**址| 视频一区在线观看| 久久久久资源| 国产欧美日本一区视频| 国产日产精品久久久久久婷婷| 精品无人区太爽高潮在线播放| 日韩美女毛片| 欧美日韩国产专区| 777电影在线观看| 国产一区二区三区久久精品| 亚洲婷婷丁香| 日韩影片在线播放| 综合亚洲深深色噜噜狠狠网站| 美女羞羞视频在线观看| 久久久999精品视频| 欧美1区视频| 亚洲国产成人精品无码区99| 欧美性69xxxx肥| 久久久久久一区二区三区四区别墅| 国产精品久久久久999| 久久草av在线| 欧洲综合视频| 欧美黄色性视频| 视频精品一区二区| av777777| 一本色道久久88亚洲综合88| 午夜久久久久| 亚洲36d大奶网| 日韩电影中文字幕在线观看| 国产精品精品国产一区二区| 动漫av网站免费观看| 制服丝袜成人动漫| 欧美人与拘性视交免费看| 亚洲午夜精品福利| 高跟丝袜一区二区三区| 精品久久国产一区| 久久精品一二三区| 亚洲国产综合91精品麻豆| 色综合.com| 日韩欧美亚洲区| 色综合久久综合| 丁香婷婷成人| 成人在线视频一区二区三区| 欧美日韩一卡二卡| 亚洲国产合集| 男人天堂成人在线| 在线播放亚洲激情| 奇米色一区二区| 色综合久久影院| 国产自产女人91一区在线观看| 国产亚洲va综合人人澡精品| 草草在线视频| 日本10禁啪啪无遮挡免费一区二区| 亚洲成av人片www| 亚洲电影一级片| 尤蜜粉嫩av国产一区二区三区| 亚洲人成在线观看网站高清| 另类图片国产| 丁香婷婷在线| 成人福利网站在线观看| 国产精品久久影院| 人人精品久久| 青青草综合在线| 亚洲精品自产拍| 久久精品国产精品亚洲综合| 污污的视频在线观看| 国产一区二区三区色淫影院| 色综合久久久网| 欧美国产精品| 四虎影视精品成人| 成人观看高清在线观看免费| 亚洲国产精品一区二区久久恐怖片 | 久久久久久久久久久久久久久久久久av | 国产韩国精品一区二区三区| 免费观看的av网站| 日本高清久久天堂| 亚洲欧美日韩国产一区二区三区 | 97人人做人人爱| 激情图区综合网| 国产视频中文字幕在线观看| 欧美在线播放一区二区| 精品国产sm最大网站| 国产一区二区三区av电影 | 一区二区三区入口| 久久不射电影网| 国产精品久久久久三级| 欧美久久综合网| 成人av一区| 一本色道久久99精品综合| 色综久久综合桃花网| 自拍偷拍欧美精品| 欧美不卡在线| 伦理在线一区| 日韩一级在线免费观看| 国产精品自拍偷拍| 91麻豆精品国产91久久久久久 | 亚洲日本韩国一区| 一区精品久久| 精品无人乱码一区二区三区| 色屁屁一区二区| 日韩毛片在线一区二区毛片| 粉嫩高清一区二区三区精品视频| 欧美挠脚心视频网站| 日韩中文字幕区一区有砖一区| 色老头在线一区二区三区| 成人黄色av片| 国产精品第100页| 欧美日韩三级在线| 久久电影国产免费久久电影| 久久久久久久性潮| 男男gay免费网站| 99免费在线观看视频| 亚洲精品电影在线观看| 国产片一区二区| 欧美福利专区| 蜜桃视频成人m3u8| 无夜福利视频观看| 欧美连裤袜在线视频| 操日韩av在线电影| 欧美午夜无遮挡| 国产曰批免费观看久久久| 日本国产精品| 精品51国产黑色丝袜高跟鞋| 116极品美女午夜一级| 国产一区二区香蕉| 一区二区中文字幕| 色拍拍在线精品视频8848| 成人午夜短视频| 真实国产乱子伦精品一区二区三区| 日韩大尺度黄色| 影院免费视频| 17c丨国产丨精品视频| 成人免费在线视频网址| www.久久撸.com| 精品视频资源站| 国产精品无码永久免费888| 日韩综合在线视频|