Maison > Java > javaDidacticiel > le corps du texte

utilisation future complétable

DDD
Libérer: 2024-08-15 14:15:30
original
258 Les gens l'ont consulté

Comment utiliser CompletableFuture pour attendre la fin de plusieurs opérations asynchrones ?

CompletableFuture fournit une méthode appelée allOf qui peut être utilisée pour attendre la fin de plusieurs opérations asynchrones. La méthode allOf prend un nombre variable d'objets CompletableFuture comme arguments et renvoie un nouveau CompletableFuture qui se termine lorsque toutes les entrées CompletableFuture sont terminés.<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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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

L'exemple de code suivant montre comment utiliser la méthode allOf pour attendre la fin de plusieurs opérations asynchrones :🎜
<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>
Copier après la connexion
🎜Comment fonctionne le mécanisme d'annulation de CompletableFuture ?🎜🎜CompletableFuture fournit une méthode cancel qui peut être utilisée pour annuler l'opération asynchrone représentée par CompletableFuture. La méthode cancel prend un argument booléen qui indique si l'annulation doit ou non être une interruption.🎜🎜Si la méthode cancel est appelée avec l'indicateur d'interruption défini sur true , l'opération asynchrone sera interrompue si elle est toujours en cours d'exécution. Si l'opération asynchrone est déjà terminée, la méthode cancel n'aura aucun effet.🎜🎜Si la méthode cancel est appelée avec l'indicateur d'interruption défini sur false code>, l'opération asynchrone sera annulée si elle n'est pas encore terminée. Si l'opération asynchrone est déjà terminée, la méthode <code>cancel n'aura aucun effet.🎜🎜L'exemple de code suivant montre comment utiliser la méthode cancel pour annuler une opération asynchrone :🎜 rrreee🎜Comment gérer les exceptions et les valeurs de retour avec CompletableFuture ?🎜🎜CompletableFuture fournit des méthodes pour gérer à la fois les exceptions et les valeurs de retour. Les méthodes thenApply et thenAccept peuvent être utilisées pour gérer les valeurs de retour, tandis que les méthodes exceptionnellement et handle peuvent être utilisées pour gérer les exceptions.🎜🎜La méthode thenApply prend une fonction comme argument et renvoie un nouveau CompletableFuture qui sera complété avec le résultat de l'application de la fonction au résultat du CompletableFuture original. L'exemple de code suivant montre comment utiliser la méthode thenApply pour gérer une valeur de retour :🎜rrreee🎜La méthode thenAccept prend un consommateur comme argument et renvoie un nouveau CompletableFuture qui sera complété lorsque le consommateur aura été appliqué au résultat du CompletableFuture original. L'exemple de code suivant montre comment utiliser la méthode thenAccept pour gérer une valeur de retour :🎜rrreee🎜La méthode exceptionnellement prend une fonction comme argument et renvoie un nouveau CompletableFuture qui sera complété avec le résultat de l'application de la fonction à l'exception qui a provoqué la fin exceptionnelle du CompletableFuture d'origine. L'exemple de code suivant montre comment utiliser la méthode exceptionnellement pour gérer une exception :🎜rrreee🎜La méthode handle prend une bi-fonction comme argument et renvoie un nouveau CompletableFuture qui sera complété avec le résultat de l'application de la bi-fonction au résultat du CompletableFuture d'origine et à l'exception qui a provoqué la fin du CompletableFuture d'origine exceptionnellement (le cas échéant). L'exemple de code suivant montre comment utiliser la méthode handle pour gérer une valeur de retour ou une exception :🎜rrreee

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!