文章目录
在 Java 异步编程中,CompletableFuture
类提供了多种方法来处理任务的依赖和执行顺序。理解这些方法如何协同工作,可以帮助我们更高效地处理复杂的异步操作。
一. thenApply()
:转换计算结果
thenApply()
方法允许我们在前一个 CompletableFuture
执行完成后,基于其计算结果执行转换操作,并返回一个新的 CompletableFuture
。这个方法非常适合用于链式转换操作,例如数据转换或映射。
1. 一个线程中执行或多个线程中执行
三个重载方法如下:
//后一个任务与前一个任务在同一个线程中执行
public <U> CompletableFuture<U> thenApply(
Function<? super T,? extends U> fn)
//后一个任务与前一个任务不在同一个线程中执行
public <U> CompletableFuture<U> thenApplyAsync(
Function<? super T,? extends U> fn)
//后一个任务在指定的executor线程池中执行
public <U> CompletableFuture<U> thenApplyAsync(
Function<? super T,? extends U> fn, Executor executor)
可以看到thenApply可以将前后任务串到一个线程中执行,或者异步执行。
2. 使用场景说明
假设你从一个异步任务中获取了一个整数结果,而你需要对其进行一些计算或转换。通过 thenApply()
,你可以轻松地对该结果进行处理。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 2);
future.thenApply(result -> result * 2) // result = 2, 返回结果是 4
.thenAccept(result -> System.out.println(result)); // 输出 4
> **分析**:
>
> - `CompletableFuture.supplyAsync(() -> 2)`:异步执行任务,返回结果 2。
> - `thenApply(result -> result * 2)`:对结果进行转换,返回 4。
> - `thenAccept(result -> System.out.println(result))`:消费结果,打印 4。
>
> `thenApply()` 适用于当我们需要基于前一个任务的计算结果执行某种转换时,它帮助我们创建一个新的异步任务,并将处理后的结果返回。
再看一个例子:
@Test
public void thenApplyDemo() throws Exception {
CompletableFuture<Long> future = CompletableFuture.supplyAsync(new Supplier<Long>() {
@Over