首页 > Java > java教程 > 正文

completablefuture 用法

DDD
发布: 2024-08-15 14:15:30
原创
258 人浏览过

如何使用 CompletableFuture 等待多个异步操作完成?

CompletableFuture 提供了一个名为 allOf 的方法,可以用来等待多个异步操作完成。 allOf 方法采用可变数量的 CompletableFuture 对象作为参数,并返回一个新的 CompletableFuture,当所有输入 CompletableFuture 对象已完成。<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 方法将不起作用。🎜🎜如果在中断标志设置为 falsecancel 方法时调用code>,如果异步操作尚未完成,则取消该操作。如果异步操作已经完成,则 cancel 方法将不起作用。🎜🎜以下代码示例展示了如何使用 cancel 方法取消异步操作:🎜 rrreee🎜如何使用 CompletableFuture 处理异常和返回值?🎜🎜CompletableFuture 提供了处理异常和返回值的方法。 thenApplythenAccept 方法可用于处理返回值,而 exceptionallyhandle 方法可用于处理返回值处理异常。🎜🎜thenApply 方法接受一个函数作为参数,并返回一个新的 CompletableFuture,该函数将完成将函数应用到原始的CompletableFuture。以下代码示例展示了如何使用 thenApply 方法来处理返回值:🎜rrreee🎜thenAccept 方法将消费者作为参数并返回一个新的 CompletableFuture 将会在消费者应用到原始 CompletableFuture 的结果时完成。以下代码示例展示了如何使用 <code>thenAccept 方法来处理返回值:🎜rrreee🎜exceptionally 方法接受一个函数作为参数并返回一个新的 CompletableFuture 将会完成,并将函数应用于导致原始 CompletableFuture 异常完成的异常。以下代码示例展示了如何使用 exceptionally 方法来处理异常:🎜rrreee🎜handle 方法采用双函数作为参数并返回一个新的 CompletableFuture 将通过将双函数应用于原始 CompletableFuture 的结果以及导致原始 CompletableFuture 完成的异常来完成例外(如果有的话)。以下代码示例展示了如何使用 handle 方法来处理返回值或异常:🎜rrreee

以上是completablefuture 用法的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!