ホームページ Java &#&チュートリアル Java での非同期マージ操作に CompletableFuture の thenCompose 関数と thenCombine 関数を使用する方法

Java での非同期マージ操作に CompletableFuture の thenCompose 関数と thenCombine 関数を使用する方法

Jun 26, 2023 pm 03:01 PM
java completablefuture thencompose thencombine 非同期マージ

Java では、非同期操作が必要なシナリオによく遭遇します。この状況に対処するために、Java 8 では CompletableFuture クラスを導入しました。このクラスは、非同期プログラミングをよりシンプルかつ簡単にするための豊富な非同期プログラミング ツールを提供します。このうち、thenCompose と thenCombine は、CompletableFuture クラスで一般的に使用される 2 つの組み合わせの非同期操作メソッドです。

1. thenCompose

thenCompose メソッドの使用は、CompletableFuture インスタンスを別の CompletableFuture インスタンスに変換するために使用されます。具体的には、以前の CompletableFuture によって返された結果を入力として受け取り、新しい CompletableFuture オブジェクトを返す Function パラメータを受け取ります。以下に例を示します。

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    // 模拟计算耗时
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 10;
});

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

result.whenComplete((res, ex) -> {
    if (ex != null) {
        ex.printStackTrace();
    } else {
        System.out.println(res);
    }
});
ログイン後にコピー

上記のコードでは、まず CompletableFuture インスタンスを作成します。これは、別のスレッドでの計算時間をシミュレートします。次に、thenCompose メソッドを使用して、それを新しい CompletableFuture インスタンスに変換します。これにより、以前の CompletableFuture によって返された結果が 2 倍されます。最後に、whenComplete メソッドを使用して、結果またはエラー メッセージを出力します。

2. thenCombine の使用

thenCombine メソッドは、2 つの CompletableFuture インスタンスを 1 つにマージするために使用されます。具体的には、別の CompletableFuture インスタンスと、2 つの CompletableFuture によって返された結果を入力として受け取り、新しい CompletableFuture オブジェクトを返す BiFunction パラメーターを受け取ります。以下に例を示します。

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
    // 模拟计算耗时
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 10;
});

CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
    // 模拟计算耗时
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 5;
});

CompletableFuture<Integer> result = future1.thenCombine(future2, (value1, value2) -> value1 + value2);

result.whenComplete((res, ex) -> {
    if (ex != null) {
        ex.printStackTrace();
    } else {
        System.out.println(res);
    }
});
ログイン後にコピー

上記のコードでは、2 つの CompletableFuture インスタンスを作成し、それぞれ 2 つのコンピューティング タスクの実行をシミュレートしました。次に、thenCombine メソッドを使用して、2 つの CompletableFuture インスタンスを新しいインスタンスにマージし、最初の 2 つの CompletableFuture によって返された結果を追加します。最後に、whenComplete メソッドを使用して、結果またはエラー メッセージを出力します。

3. thenCompose と thenCombine を使用して複雑な非同期操作を実装する

thenCompose メソッドと thenCombine メソッドの使用法をすでに紹介しましたが、どちらも非常に便利な非同期操作メソッドです。実際、これらを使用して、複数の計算結果に対する集計操作など、より複雑な非同期操作を実装することもできます。

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
    // 模拟计算耗时
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 10;
});

CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
    // 模拟计算耗时
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 5;
});

CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
    // 模拟计算耗时
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 20;
});

CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2, future3);

CompletableFuture<Integer> result = combinedFuture.thenCompose(
        voidResult -> CompletableFuture.supplyAsync(() -> {
            int sum = future1.join() + future2.join() + future3.join();
            return sum;
        }));

result.whenComplete((res, ex) -> {
    if (ex != null) {
        ex.printStackTrace();
    } else {
        System.out.println(res);
    }
});
ログイン後にコピー

上記のコードでは、3 つの CompletableFuture インスタンスを作成しました。それぞれがコンピューティング タスクの実行をシミュレートし、対応する結果を返します。次に、CompletableFuture.allOf メソッドを使用して、これら 3 つのインスタンスを結合し、新しい CompletableFuture インスタンスを作成します。ここで、allOf メソッドは Void 型の CompletableFuture インスタンスを返し、その戻り値は null であることに注意してください。

次に、thenCompose メソッドを使用して、null を返す上記の CompletableFuture インスタンスを新しい CompletableFuture インスタンスに変換します。これにより、前の 3 つの CompletableFuture によって返された結果が追加されます。 thenCompose メソッドのコールバック関数では、join() メソッドを使用して各 CompletableFuture インスタンスの結果値を取得し、対応する計算を実行します。最後に、whenComplete メソッドを使用して、結果またはエラー メッセージを出力します。

一般に、thenCompose と thenCombine は CompletableFuture クラスの非常に便利なメソッドであり、非同期操作をより便利に実行し、プログラムの同時実行性と実行効率を向上させるのに役立ちます。

以上がJava での非同期マージ操作に CompletableFuture の thenCompose 関数と thenCombine 関数を使用する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)