CompletableFuture的入門

来源:https://www.cnblogs.com/hitechr/archive/2022/06/29/16423413.html
-Advertisement-
Play Games

runAsync 和 supplyAsync runAsync接受一個Runable的實現,無返回值 CompletableFuture.runAsync(()->System.out.println("無返回結果的運行")); supplyAsync接受一個Supplier的實現,有返回值 Com ...


runAsync 和 supplyAsync

runAsync接受一個Runable的實現,無返回值

CompletableFuture.runAsync(()->System.out.println("無返回結果的運行"));

supplyAsync接受一個Supplier的實現,有返回值

CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
      System.out.println("有返回結果的運行");
      return 1;
  });

獲取結果的get和join

都是堵塞,直到返回結果
get方法拋出是經過處理的異常,ExecutionException或**InterruptedException **,需要用戶手動捕獲

try {
   System.out.println(CompletableFuture.supplyAsync(() -> {
    System.out.println("有返回結果的運行");
    return 1;
  }).get());
} catch (InterruptedException e) {
  e.printStackTrace();
} catch (ExecutionException e) {
  e.printStackTrace();
}

join方法拋出的就不用捕獲,是經過包裝的**CompletionException **或 CancellationException

        System.out.println(CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("有返回結果的運行");
            return 1;
        }).join());

常用方法

獲取結果的get\join\getNow

get():一直等待
get(timeout,unit):等待,除非超時
getNow(valueIfAbsent):計算完返回計算的結果,未計算完返回預設的結果

CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {

            try {
                TimeUnit.SECONDS.sleep(1);
                ;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 1;
        });

        System.out.println("立即獲取:"+completableFuture.getNow(9999));
        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println("doing");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("等一會獲取:"+completableFuture.getNow(9999));

join() 同get()

thenApply\handle

執行完前面的,前面返回的結果返回,然後傳給後面再,執行完後面任務,一步一步來。

CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
    System.out.println("step 1");
    return 1;
}).thenApply(a -> {
    System.out.println("step 2");
    return a + 2;
}).thenApply(a -> {
    System.out.println("step 3");
    return a + 3;
});
System.out.println(completableFuture.get());

執行結果:

CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
    System.out.println("step 1");
    int a=1/0;
    return 1;
}).handle((a,b) -> {
    System.out.println("step 2");
    if (b!=null) {
        System.out.println(b.getMessage());
        return 0;
    }
    return a + 2;
}).handle((a,b) -> {
    System.out.println("step 3");
    if (b!=null) {
        System.out.println(b.getMessage());
        return 0;
    }
    return a + 3;
});
System.out.println(completableFuture.get());

執行結果:

thenApply和handle的區別:
thenApply執行的時候,有異常的則整個執行鏈會中斷,直接拋出異常。

handle有異常也可以往下一步走,根據帶的異常參數可以進一步處理

thenAccept

接收前面任務的返回結果,當前節點處理,並不返回結果。

CompletableFuture.supplyAsync(()->{
    System.out.println("step 1");
    return 10;
}).thenAccept(a->{
    System.out.println("res "+a);
});

applyToEither

在多個任務段同時執行時,哪個任務段用時最少,就返回哪個

CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
    System.out.println("step 1");
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 1;
}).applyToEither(CompletableFuture.supplyAsync(() -> {
    System.out.println("step 2");
    try {
        TimeUnit.SECONDS.sleep(2);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 2;
}), a -> {
    return a;
});
System.out.println(completableFuture.get());

執行結果:

thenCombine

合併多個任務段的返回結果

CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("step 1");
            return IntStream.range(1, 11).sum();
        }).thenCombine(CompletableFuture.supplyAsync(() -> {
            System.out.println("step 2");
            return IntStream.range(11, 21).sum();
        }), (a, b) -> a + b)
        .thenCombine(CompletableFuture.supplyAsync(() -> {
            System.out.println("step 3");
            return IntStream.range(21, 31).sum();
        }), (a, b) -> a + b);
System.out.println(completableFuture.get());

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 昨晚我正在床上睡得著著的,突然來了一條簡訊。 啥,線上MySQL死鎖了,我趕緊登錄線上系統,查看業務日誌。 ...
  • 打開源代碼發現了個./time.php?source 於是打開點進去 <?php #error_reporting(0); class HelloPhp { public $a; public $b; public function __construct(){ $this->a = "Y-m-d ...
  • 來源:blog.csdn.net/qq_29879799/article/details/105146415 java的stream編程給調試帶來了極大的不便,idea 推出了streamtrace功能,可以詳細看到每一步操作的關係、結果,非常方便進行調試。 初遇StreamTrace 這裡簡單將字 ...
  • The DataStream API gets its name from the special DataStream class that is used to represent a collection of data in a Flink program. You can think of ...
  • 參考:(17條消息) 手把手搭建一個完整的javaweb項目(適合新手)_心歌技術的博客-CSDN博客_javaweb項目完整案例 補充項目結構的細節,進行了一點修改,修改為學生信息管理系統 以下是搭建過程: 1.項目結構 2.資料庫結構 3.代碼部分 com.dao.StuDao.java pac ...
  • 背景:[JAVA]前幾天面試超碧,聊到其接觸的項目,有抓取各類排行的實時數據,進行多國語言翻譯,抓取目前比較火的語言是php、go,由於目前工作使用JAVA,因此也模擬實現了一下抓取百度熱搜榜實時數據。 效果: 步驟: 1、定址【百度熱搜榜】https://top.baidu.com/board?t ...
  • java集合 學習資源:b站 人人都是程式員 《看動畫學java集合》 b站 韓順平 《java集合》 感謝二位的開源視頻,本博客為個人筆記,如有錯誤還請包涵 學習方法:推薦觀看視頻,自己用idea敲一遍然後debug一步步看,最後自己寫筆記和畫流程圖。 前 言 目的:為了方便和高效地存儲大批量的數 ...
  • Hi,大家好,我是Mic。 一個工作5年的粉絲,在簡歷上寫精通Kafka。 結果在面試的時候直接打臉。 面試官問他:“什麼是ISR,為什麼需要設計ISR” 然後他一臉懵逼的看著面試官. 下麵看看普通人和高手的回答。 普通人: ISR好像是Kafka裡面的一個機制吧。 為什麼要引入,應該是跟數據同步有 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...