Completable Future を使用した Java でのマルチスレッドの処理

WBOY
リリース: 2024-09-08 22:35:03
オリジナル
577 人が閲覧しました

Handling Multithreading in Java with Completable Future

1. 完成可能な未来を理解する

CompletableFuturejava.util.concurrent パッケージの一部であり、より読みやすく保守しやすい方法で非同期のノンブロッキング コードを作成する方法を提供します。これは、非同期計算の将来の結果を表します。

1.1 単純な CompletableFuture の作成

CompletableFuture から始めると、単純な非同期タスクを作成できます。以下に例を示します:

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.out.println("Running asynchronously...");
            // Simulate a long-running task
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        future.join(); // Wait for the task to complete
        System.out.println("Task completed.");
    }
}
ログイン後にコピー
  • CompletableFuture.runAsync() はタスクを非同期で実行します。
  • future.join() は、タスクが完了するまでメインスレッドをブロックします。

デモ結果:

Running asynchronously...
Task completed.
ログイン後にコピー

1.2 結果での CompletableFuture の使用

CompletableFuture を使用して、非同期タスクからの結果を返すこともできます。

import java.util.concurrent.CompletableFuture;

public class CompletableFutureWithResult {
    public static void main(String[] args) {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            // Simulate a computation
            return 5 * 5;
        });

        future.thenAccept(result -> {
            System.out.println("The result is: " + result);
        }).join();
    }
}
ログイン後にコピー
  • CompletableFuture.supplyAsync() は、結果を返すタスクに使用されます。
  • thenAccept() は、計算が完了すると結果を処理します。

デモ結果:

The result is: 25
ログイン後にコピー

2. 複数の CompletableFuture の結合

複数の非同期タスクの処理は一般的な使用例です。 CompletableFuture は、先物を結合するためのいくつかのメソッドを提供します。

2.1 thenCombine を使用して先物を結合する

複数の CompletableFutures からの結果を組み合わせることができます:

import java.util.concurrent.CompletableFuture;

public class CombiningFutures {
    public static void main(String[] args) {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 5);
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 10);

        CompletableFuture<Integer> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + result2);

        combinedFuture.thenAccept(result -> {
            System.out.println("Combined result: " + result);
        }).join();
    }
}
ログイン後にコピー
  • thenCombine () は 2 つの先物の結果を結合します。
  • 結合された結果は、thenAccept ().
  • を使用して処理されます。

デモ結果:

Combined result: 15
ログイン後にコピー

2.2 allOf による複数の Future の処理

複数の Future が完了するまで待つ必要がある場合は、CompletableFuture.allOf():
を使用します。

import java.util.concurrent.CompletableFuture;

public class AllOfExample {
    public static void main(String[] args) {
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            // Simulate task
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            // Simulate another task
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

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

        allOfFuture.join();
        System.out.println("All tasks completed.");
    }
}
ログイン後にコピー
  • CompletableFuture.allOf() は、指定されたすべての Future が完了するまで待機します。
  • join() は、すべてのタスクが完了するまでメインスレッドを待機させます。

デモ結果:

All tasks completed.
ログイン後にコピー

3. CompletableFuture によるエラー処理

非同期プログラミングではエラーの処理が不可欠です。 CompletableFuture は、例外を管理するメソッドを提供します。

3.1 例外処理による例外処理

非同期タスクの例外を処理するには、例外的に () を使用します:

import java.util.concurrent.CompletableFuture;

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            throw new RuntimeException("Something went wrong!");
        }).exceptionally(ex -> {
            System.out.println("Exception occurred: " + ex.getMessage());
            return null;
        });

        future.join();
    }
}
ログイン後にコピー
  • 例外的に () は例外をキャッチして処理します。
  • フォールバック結果を提供したり、エラーを処理したりできます。

デモ結果:

Exception occurred: Something went wrong!
ログイン後にコピー

4. CompletableFuture のメリットとデメリット

4.1 利点

  • 非同期実行 : メインスレッドをブロックせずに、同時に実行されるタスクを効率的に処理します。
  • 可読性の向上 : 従来のコールバック アプローチと比較して、非同期コードを処理するための、より読みやすく保守しやすい方法を提供します。
  • リッチ API : 複数の Future を結合、処理、構成するためのさまざまなメソッドを提供します。

4.2 欠点

  • 複雑さ : CompletableFuture は強力ですが、非同期コードの管理とデバッグが複雑になる可能性があります。
  • 例外処理: 例外の処理は、特に複数の段階がある複雑なシナリオでは難しい場合があります。

5. 結論

このガイドでは、Java での同時リクエストを処理するために CompletableFuture を使用する方法を検討しました。単純な非同期タスクの作成から、複数の Future の組み合わせやエラーの処理に至るまで、CompletableFuture は非同期プログラミングに対する堅牢かつ柔軟なアプローチを提供します。

ご質問がある場合、またはさらにサポートが必要な場合は、お気軽に以下にコメントを残してください。喜んでお手伝いさせていただきます!

詳細については、 で投稿をご覧ください: Completable Future を使用した Java でのマルチスレッドの処理

以上がCompletable Future を使用した Java でのマルチスレッドの処理の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!