ホームページ  >  記事  >  Java  >  完了可能将来の使用法

完了可能将来の使用法

DDD
DDDオリジナル
2024-08-15 14:15:30259ブラウズ

CompletableFuture を使用して複数の非同期操作の完了を待機する方法?

CompletableFuture には、複数の非同期操作の完了を待機するために使用できる allOf というメソッドが用意されています。 allOf メソッドは、可変数の CompletableFuture オブジェクトを引数として受け取り、すべての入力 CompletableFutureCompletableFuture を返します。 /code> オブジェクトが完了しました。allOf that can be used to wait for multiple asynchronous operations to complete. The allOf method takes a variable number of CompletableFuture objects as arguments and returns a new CompletableFuture that completes when all of the input CompletableFuture objects have completed.

The following code sample shows how to use the allOf method to wait for multiple asynchronous operations to complete:

<code class="java">CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<Void> allOf = CompletableFuture.allOf(future1, future2);

allOf.join();

System.out.println(future1.get()); // Prints "Hello"
System.out.println(future2.get()); // Prints "World"</code>

How does CompletableFuture's cancellation mechanism work?

CompletableFuture provides a cancel method that can be used to cancel the asynchronous operation represented by the CompletableFuture. The cancel method takes a boolean argument that indicates whether or not the cancellation should be interrupting.

If the cancel method is called with the interrupting flag set to true, the asynchronous operation will be interrupted if it is still running. If the asynchronous operation has already completed, the cancel method will have no effect.

If the cancel method is called with the interrupting flag set to false, the asynchronous operation will be cancelled if it has not yet completed. If the asynchronous operation has already completed, the cancel method will have no effect.

The following code sample shows how to use the cancel method to cancel an asynchronous operation:

<code class="java">CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return "Hello World";
});

future.cancel(true); // Interrupt the asynchronous operation

if (future.isCancelled()) {
    System.out.println("The asynchronous operation was cancelled.");
}</code>

How to handle exceptions and return values with CompletableFuture?

CompletableFuture provides methods for handling both exceptions and return values. The thenApply and thenAccept methods can be used to handle return values, while the exceptionally and handle methods can be used to handle exceptions.

The thenApply method takes a function as an argument and returns a new CompletableFuture that will be completed with the result of applying the function to the result of the original CompletableFuture. The following code sample shows how to use the thenApply method to handle a return value:

<code class="java">CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello World");

CompletableFuture<Integer> future2 = future.thenApply(s -> s.length());

future2.join();

System.out.println(future2.get()); // Prints 11</code>

The thenAccept method takes a consumer as an argument and returns a new CompletableFuture that will be completed when the consumer has been applied to the result of the original CompletableFuture. The following code sample shows how to use the thenAccept method to handle a return value:

<code class="java">CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello World");

CompletableFuture<Void> future2 = future.thenAccept(s -> System.out.println(s));

future2.join(); // Prints "Hello World"</code>

The exceptionally method takes a function as an argument and returns a new CompletableFuture that will be completed with the result of applying the function to the exception that caused the original CompletableFuture to complete exceptionally. The following code sample shows how to use the exceptionally method to handle an exception:

<code class="java">CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("Error!");
});

CompletableFuture<String> future2 = future.exceptionally(e -> "Error occurred: " + e.getMessage());

future2.join();

System.out.println(future2.get()); // Prints "Error occurred: java.lang.RuntimeException: Error!"</code>

The handle method takes a bi-function as an argument and returns a new CompletableFuture that will be completed with the result of applying the bi-function to the result of the original CompletableFuture and the exception that caused the original CompletableFuture to complete exceptionally (if any). The following code sample shows how to use the handle

次のコード サンプルは、allOf メソッドを使用して複数の非同期操作が完了するのを待つ方法を示しています:🎜
<code class="java">CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    if (Math.random() > 0.5) {
        return "Success";
    } else {
        throw new RuntimeException("Error!");
    }
});

CompletableFuture<String> future2 = future.handle((result, exception) -> {
    if (exception != null) {
        return "Error occurred: " + exception.getMessage();
    } else {
        return result;
    }
});

future2.join();

System.out.println(future2.get()); // Prints "Success" or "Error occurred: java.lang.RuntimeException: Error!"</code>
🎜 CompletableFuture のキャンセル メカニズムはどのように機能しますか?🎜🎜CompletableFuture は提供しますcancel メソッド。CompletableFuture で表される非同期操作をキャンセルするために使用できます。 cancel メソッドは、キャンセルを中断するかどうかを示すブール値の引数を受け取ります。🎜🎜cancel メソッドが中断フラグを true に設定して呼び出された場合 を実行すると、非同期操作がまだ実行中の場合は中断されます。非同期操作がすでに完了している場合、cancel メソッドは効果がありません。🎜🎜中断フラグを false に設定して <code>cancel メソッドが呼び出された場合code> の場合、非同期操作がまだ完了していない場合はキャンセルされます。非同期操作がすでに完了している場合、cancel メソッドは効果がありません。🎜🎜次のコード サンプルは、cancel メソッドを使用して非同期操作をキャンセルする方法を示しています。🎜 rrreee🎜CompletableFuture で例外と戻り値を処理する方法🎜🎜CompletableFuture は、例外と戻り値の両方を処理するメソッドを提供します。 thenApply メソッドと thenAccept メソッドは戻り値の処理に使用できますが、Exceptionally メソッドと handle メソッドは戻り値の処理に使用できます。 🎜🎜 thenApply メソッドは関数を引数として受け取り、関数を関数の結果に適用した結果で完了する新しい CompletableFuture を返します。オリジナルの CompletableFuture。次のコード サンプルは、thenApply メソッドを使用して戻り値を処理する方法を示しています。🎜rrreee🎜 thenAccept メソッドは引数としてコンシューマを受け取り、新しい を返します。 CompletableFuture は、コンシューマが元の CompletableFuture の結果に適用されたときに完了します。次のコード サンプルは、thenAccept メソッドを使用して戻り値を処理する方法を示しています。🎜rrreee🎜 例外的に メソッドは引数として関数を受け取り、新しい を返します。 CompletableFuture は、元の CompletableFuture が例外的に完了する原因となった例外に関数を適用した結果で完了します。次のコード サンプルは、例外的に メソッドを使用して例外を処理する方法を示しています。🎜rrreee🎜 handle メソッドは引数として二重関数を受け取り、新しい を返します。 >CompletableFuture。これは、元の CompletableFuture の結果に二重関数を適用した結果と、元の CompletableFuture を完了させる原因となった例外で完了します。例外的に(もしあれば)。次のコード サンプルは、handle メソッドを使用して戻り値または例外を処理する方法を示しています。

以上が完了可能将来の使用法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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