亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java使用CompletableFuture實現(xiàn)異步編程

 更新時間:2025年01月16日 11:08:07   作者:加瓦點燈  
在現(xiàn)代 Java 開發(fā)中,異步編程是一項重要技能,而 CompletableFuture 是從 Java 8 開始提供的一個功能強大的工具,用于簡化異步任務的編寫和組合,本文將詳細介紹 CompletableFuture 的基本使用和一些常見的應用場景,需要的朋友可以參考下

1. 為什么選擇 CompletableFuture?

傳統(tǒng)的異步編程通常依賴于回調或 Future,但這些方法存在一些缺陷:

  • 回調地獄:嵌套層級多,代碼難以閱讀。
  • Future 的 get() 方法是阻塞的,無法真正實現(xiàn)非阻塞式編程。

CompletableFuture 的優(yōu)勢在于:

  • 支持非阻塞操作。
  • 提供豐富的 API 用于任務的組合和處理。
  • 更好的錯誤處理機制。

2. 基本用法

創(chuàng)建一個 CompletableFuture

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        // 創(chuàng)建一個異步任務
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000); // 模擬耗時操作
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "Hello, CompletableFuture!";
        });

        // 非阻塞地獲取結果
        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. 任務組合

thenApply: 轉換結果

thenApply 方法用于將異步任務的結果轉換為另一種類型。

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> "42")
    .thenApply(Integer::parseInt)
    .thenApply(num -> num * 2);

future.thenAccept(result -> System.out.println("Final Result: " + result));

thenCompose: 鏈式調用

thenCompose 用于在一個任務完成后啟動另一個異步任務。

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World!"));

future.thenAccept(System.out::println);

thenCombine: 合并兩個任務

thenCombine 用于合并兩個獨立的異步任務的結果。

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. 異常處理

在異步任務中,異常處理非常重要。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: 處理結果和異常

handle 方法無論任務成功還是失敗都會執(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. 實際應用場景

并發(fā)請求處理

在需要同時處理多個請求時,可以利用 allOf 或 anyOf 方法。

allOf: 等待所有任務完成

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: 任意任務完成即返回

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. 總結

CompletableFuture 是 Java 異步編程的強大工具,提供了豐富的 API 來實現(xiàn)任務的創(chuàng)建、組合和異常處理。通過熟練掌握 CompletableFuture,可以編寫更加簡潔高效的異步代碼。

以上就是Java使用CompletableFuture實現(xiàn)異步編程的詳細內容,更多關于Java CompletableFuture異步編程的資料請關注腳本之家其它相關文章!

相關文章

  • 淺談Java數(shù)據(jù)結構之稀疏數(shù)組知識總結

    淺談Java數(shù)據(jù)結構之稀疏數(shù)組知識總結

    今天帶大家了解一下Java稀疏數(shù)組的相關知識,文中有非常詳細的介紹及代碼示例,對正在學習java的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-05-05
  • Spring?Cloud?Gateway?遠程代碼執(zhí)行漏洞(CVE-2022-22947)的過程解析

    Spring?Cloud?Gateway?遠程代碼執(zhí)行漏洞(CVE-2022-22947)的過程解析

    Spring?Cloud?Gateway?是基于?Spring?Framework?和?Spring?Boot?構建的?API?網關,它旨在為微服務架構提供一種簡單、有效、統(tǒng)一的?API?路由管理方式,這篇文章主要介紹了Spring?Cloud?Gateway?遠程代碼執(zhí)行漏洞(CVE-2022-22947),需要的朋友可以參考下
    2022-08-08
  • Java Kafka分區(qū)發(fā)送及消費實戰(zhàn)

    Java Kafka分區(qū)發(fā)送及消費實戰(zhàn)

    本文主要介紹了Kafka分區(qū)發(fā)送及消費實戰(zhàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • SpringBoot多數(shù)據(jù)源配置詳細教程(JdbcTemplate、mybatis)

    SpringBoot多數(shù)據(jù)源配置詳細教程(JdbcTemplate、mybatis)

    這篇文章主要介紹了SpringBoot多數(shù)據(jù)源配置詳細教程(JdbcTemplate、mybatis),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03
  • 淺析Spring?中?Bean?的理解與使用

    淺析Spring?中?Bean?的理解與使用

    這篇文章主要介紹了Spring?中?Bean?的理解與使用,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-03-03
  • Java service層獲取HttpServletRequest工具類的方法

    Java service層獲取HttpServletRequest工具類的方法

    今天小編就為大家分享一篇關于Java service層獲取HttpServletRequest工具類的方法,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • 解決mybatisPlus 中的field-strategy配置失效問題

    解決mybatisPlus 中的field-strategy配置失效問題

    這篇文章主要介紹了解決mybatisPlus 中的field-strategy配置失效問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • Springcloud GateWay網關配置過程圖解

    Springcloud GateWay網關配置過程圖解

    這篇文章主要介紹了Springcloud GateWay網關配置過程圖解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-12-12
  • 關于@Component注解下的類無法@Autowired問題

    關于@Component注解下的類無法@Autowired問題

    這篇文章主要介紹了關于@Component注解下的類無法@Autowired問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Java動態(tài)編譯執(zhí)行代碼示例

    Java動態(tài)編譯執(zhí)行代碼示例

    這篇文章主要介紹了Java動態(tài)編譯執(zhí)行代碼示例,具有一定借鑒價值,需要的朋友可以參考下。
    2017-12-12

最新評論