赞
踩
CompletableFuture
是 Java 8 引入的一个类,位于 java.util.concurrent
包中。它结合了 Future
和 CompletionStage
的功能,允许以非阻塞的方式处理异步任务,并提供了丰富的 API 来处理任务的完成、合并、处理结果和异常等操作。
CompletableFuture
可以通过多种方式创建 CompletableFuture
实例:
CompletableFuture
:CompletableFuture<String> completedFuture = CompletableFuture.completedFuture("Hello");
supplyAsync
创建异步任务:CompletableFuture<String> asyncFuture = CompletableFuture.supplyAsync(() -> {
// 异步执行的任务
return "Hello from async task";
});
thenApply
和 thenAccept
thenApply
:当 CompletableFuture
完成时,处理结果并返回另一个结果。CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(result -> result + " World");
future.thenAccept(System.out::println); // 输出 "Hello World"
thenAccept
:当 CompletableFuture
完成时,处理结果但不返回任何结果。CompletableFuture.supplyAsync(() -> "Hello")
.thenAccept(result -> System.out.println(result + " World"));
CompletableFuture
thenCombine
:当两个 CompletableFuture
都完成时,合并它们的结果。CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + " " + result2);
combinedFuture.thenAccept(System.out::println); // 输出 "Hello World"
allOf
和 anyOf
:等待多个 CompletableFuture
完成。CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Task1");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Task2");
CompletableFuture<Void> allOfFuture = CompletableFuture.allOf(future1, future2);
allOfFuture.thenRun(() -> System.out.println("All tasks completed"));
exceptionally
:当 CompletableFuture
完成时处理异常。CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
if (true) {
throw new RuntimeException("Something went wrong!");
}
return "Hello";
}).exceptionally(ex -> "Error: " + ex.getMessage());
future.thenAccept(System.out::println); // 输出 "Error: Something went wrong!"
handle
:无论是否发生异常,都可以处理结果或异常。CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
if (true) {
throw new RuntimeException("Something went wrong!");
}
return "Hello";
}).handle((result, ex) -> {
if (ex != null) {
return "Error: " + ex.getMessage();
} else {
return result;
}
});
future.thenAccept(System.out::println); // 输出 "Error: Something went wrong!"
以下是一个完整的示例,演示了如何使用 CompletableFuture
异步地执行任务,并处理结果和异常:
import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class CompletableFutureDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new IllegalStateException(e); } return "Hello"; }); // 处理结果 CompletableFuture<String> resultFuture = future.thenApply(result -> result + " World"); // 异常处理 CompletableFuture<String> errorHandledFuture = resultFuture.exceptionally(ex -> "Error: " + ex.getMessage()); // 打印结果 errorHandledFuture.thenAccept(System.out::println); // 阻塞等待所有任务完成 CompletableFuture<Void> allDone = CompletableFuture.allOf(future, resultFuture, errorHandledFuture); allDone.get(); } }
CompletableFuture
提供了强大的异步编程能力,使得处理复杂的异步逻辑变得更加简单和直观。通过使用它的丰富 API,可以轻松地处理任务的完成、合并结果和异常处理等操作,从而大大简化了异步编程的复杂性。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。