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: 鏈?zhǔn)秸{(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)文章
詳解SpringCloudGateway內(nèi)存泄漏問題
這篇文章主要介紹了詳解SpringCloudGateway內(nèi)存泄漏問題,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
springboot+springsecurity如何實現(xiàn)動態(tài)url細粒度權(quán)限認證
這篇文章主要介紹了springboot+springsecurity如何實現(xiàn)動態(tài)url細粒度權(quán)限認證的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
Java基礎(chǔ)篇_有關(guān)接口和抽象類的幾道練習(xí)題(分享)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)篇_有關(guān)接口和抽象類的幾道練習(xí)題(分享)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06
Seata集成Mybatis-Plus解決多數(shù)據(jù)源事務(wù)問題
當(dāng)進行業(yè)務(wù)操作時,訂單發(fā)生異常 ,進行了回滾操作,因為在不同的數(shù)據(jù)庫實例中,余額卻扣除成功,此時發(fā)現(xiàn)數(shù)據(jù)不一致問題,本文給大家介紹Seata集成Mybatis-Plus解決多數(shù)據(jù)源事務(wù)問題,感興趣的朋友一起看看吧2023-11-11

