Java使用CompletableFuture實現(xiàn)異步編程
1. 為什么選擇 CompletableFuture?
傳統(tǒng)的異步編程通常依賴于回調(diào)或 Future,但這些方法存在一些缺陷:
- 回調(diào)地獄:嵌套層級多,代碼難以閱讀。
- Future 的
get()方法是阻塞的,無法真正實現(xiàn)非阻塞式編程。
CompletableFuture 的優(yōu)勢在于:
- 支持非阻塞操作。
- 提供豐富的 API 用于任務(wù)的組合和處理。
- 更好的錯誤處理機制。
2. 基本用法
創(chuàng)建一個 CompletableFuture
import java.util.concurrent.CompletableFuture;
public class CompletableFutureExample {
public static void main(String[] args) {
// 創(chuàng)建一個異步任務(wù)
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000); // 模擬耗時操作
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "Hello, CompletableFuture!";
});
// 非阻塞地獲取結(jié)果
future.thenAccept(result -> System.out.println("Result: " + result));
System.out.println("Main thread is not blocked");
// 防止主線程退出過早
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
輸出
Main thread is not blocked Result: Hello, CompletableFuture!
3. 任務(wù)組合
thenApply: 轉(zhuǎn)換結(jié)果
thenApply 方法用于將異步任務(wù)的結(jié)果轉(zhuǎn)換為另一種類型。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> "42")
.thenApply(Integer::parseInt)
.thenApply(num -> num * 2);
future.thenAccept(result -> System.out.println("Final Result: " + result));
thenCompose: 鏈式調(diào)用
thenCompose 用于在一個任務(wù)完成后啟動另一個異步任務(wù)。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World!"));
future.thenAccept(System.out::println);
thenCombine: 合并兩個任務(wù)
thenCombine 用于合并兩個獨立的異步任務(wù)的結(jié)果。
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World"); CompletableFuture<String> result = future1.thenCombine(future2, (s1, s2) -> s1 + " " + s2); result.thenAccept(System.out::println);
4. 異常處理
在異步任務(wù)中,異常處理非常重要。CompletableFuture 提供了多種方法來優(yōu)雅地處理異常。
exceptionally: 捕獲異常并返回默認值
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
if (true) {
throw new RuntimeException("Something went wrong");
}
return "Success";
}).exceptionally(ex -> {
System.out.println("Exception: " + ex.getMessage());
return "Default Value";
});
future.thenAccept(System.out::println);
handle: 處理結(jié)果和異常
handle 方法無論任務(wù)成功還是失敗都會執(zhí)行,并可以訪問異常信息。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
if (true) {
throw new RuntimeException("Error occurred");
}
return "Success";
}).handle((result, ex) -> {
if (ex != null) {
System.out.println("Exception: " + ex.getMessage());
return "Recovered from error";
}
return result;
});
future.thenAccept(System.out::println);
5. 實際應(yīng)用場景
并發(fā)請求處理
在需要同時處理多個請求時,可以利用 allOf 或 anyOf 方法。
allOf: 等待所有任務(wù)完成
CompletableFuture<Void> allTasks = CompletableFuture.allOf(
CompletableFuture.runAsync(() -> System.out.println("Task 1")),
CompletableFuture.runAsync(() -> System.out.println("Task 2")),
CompletableFuture.runAsync(() -> System.out.println("Task 3"))
);
allTasks.thenRun(() -> System.out.println("All tasks completed"));
anyOf: 任意任務(wù)完成即返回
CompletableFuture<Object> anyTask = CompletableFuture.anyOf(
CompletableFuture.supplyAsync(() -> "Task 1 completed"),
CompletableFuture.supplyAsync(() -> "Task 2 completed")
);
anyTask.thenAccept(result -> System.out.println("First completed: " + result));
6. 總結(jié)
CompletableFuture 是 Java 異步編程的強大工具,提供了豐富的 API 來實現(xiàn)任務(wù)的創(chuàng)建、組合和異常處理。通過熟練掌握 CompletableFuture,可以編寫更加簡潔高效的異步代碼。
以上就是Java使用CompletableFuture實現(xiàn)異步編程的詳細內(nèi)容,更多關(guān)于Java CompletableFuture異步編程的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
淺談Java數(shù)據(jù)結(jié)構(gòu)之稀疏數(shù)組知識總結(jié)
今天帶大家了解一下Java稀疏數(shù)組的相關(guān)知識,文中有非常詳細的介紹及代碼示例,對正在學(xué)習(xí)java的小伙伴們有很好地幫助,需要的朋友可以參考下2021-05-05
Spring?Cloud?Gateway?遠程代碼執(zhí)行漏洞(CVE-2022-22947)的過程解析
Spring?Cloud?Gateway?是基于?Spring?Framework?和?Spring?Boot?構(gòu)建的?API?網(wǎng)關(guān),它旨在為微服務(wù)架構(gòu)提供一種簡單、有效、統(tǒng)一的?API?路由管理方式,這篇文章主要介紹了Spring?Cloud?Gateway?遠程代碼執(zhí)行漏洞(CVE-2022-22947),需要的朋友可以參考下2022-08-08
Java Kafka分區(qū)發(fā)送及消費實戰(zhàn)
本文主要介紹了Kafka分區(qū)發(fā)送及消費實戰(zhàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
SpringBoot多數(shù)據(jù)源配置詳細教程(JdbcTemplate、mybatis)
這篇文章主要介紹了SpringBoot多數(shù)據(jù)源配置詳細教程(JdbcTemplate、mybatis),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
Java service層獲取HttpServletRequest工具類的方法
今天小編就為大家分享一篇關(guān)于Java service層獲取HttpServletRequest工具類的方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12
解決mybatisPlus 中的field-strategy配置失效問題
這篇文章主要介紹了解決mybatisPlus 中的field-strategy配置失效問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
Springcloud GateWay網(wǎng)關(guān)配置過程圖解
這篇文章主要介紹了Springcloud GateWay網(wǎng)關(guān)配置過程圖解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-12-12
關(guān)于@Component注解下的類無法@Autowired問題
這篇文章主要介紹了關(guān)于@Component注解下的類無法@Autowired問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03

