CompletableFuture
是 Java 中用于处理异步任务的一个强大工具,它提供了丰富的方法来管理异步任务的完成、组合以及异常处理。下面是一些常见的 CompletableFuture
方法的用法和示例:
创建 CompletableFuture
CompletableFuture.supplyAsync(Supplier<U> supplier)
这个方法接受一个 Supplier
参数,返回一个 CompletableFuture
,它会在一个新的线程中执行这个 Supplier,并返回结果。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 异步任务逻辑
return "Hello";
});
CompletableFuture.runAsync(Runnable runnable)
这个方法接受一个 Runnable
参数,返回一个 CompletableFuture<Void>
,它会在一个新的线程中执行这个 Runnable。
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
// 异步任务逻辑
System.out.println("Async task running");
});
链式调用
thenApply(Function<? super T,? extends U> fn)
在异步任务完成后,对任务的结果应用一个函数,并返回一个新的 CompletableFuture
。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(result -> result + " World");
thenAccept(Consumer<? super T> action)
在异步任务完成后,对任务的结果执行一个操作,但不返回新的结果。
CompletableFuture.supplyAsync(() -> "Hello")
.thenAccept(result -> System.out.println("Received: " + result));
thenRun(Runnable action)
在异步任务完成后,执行一个操作,不接受任务结果。
CompletableFuture.supplyAsync(() -> "Hello")
.thenRun(() -> System.out.println("Async task completed"));
组合多个 CompletableFuture
thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
组合两个 CompletableFuture
的结果,对结果应用一个函数,并返回一个新的 CompletableFuture
。
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + " " + result2);
thenCompose(Function<? super T,? extends CompletionStage<U>> fn)
对一个异步任务的结果进行处理,返回一个新的 CompletableFuture
,并且这个新的 CompletableFuture 依赖于原始任务的结果。
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = future1.thenCompose(result -> CompletableFuture.supplyAsync(() -> result + " World"));
异常处理
exceptionally(Function<Throwable, ? extends T> fn)
处理异步任务的异常情况,并返回一个默认值或者补偿结果。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 异步任务逻辑,可能会抛出异常
throw new RuntimeException("Error occurred");
}).exceptionally(ex -> "Handled Exception: " + ex.getMessage());
handle(BiFunction<? super T, Throwable, ? extends U> fn)
在异步任务完成或者抛出异常时进行处理,并返回一个新的结果。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 异步任务逻辑,可能会抛出异常
throw new RuntimeException("Error occurred");
}).handle((result, ex) -> {
if (ex != null) {
return "Handled Exception: " + ex.getMessage();
} else {
return result;
}
});
这些只是 CompletableFuture
类提供的一些方法中的一部分,还有许多其他方法可供使用,这些方法可以满足更复杂的异步编程需求。