import java.util.concurrent.CompletableFuture;
public class CompletableFutureExample {
public static void main(String[] args) {
// 模拟已经完成计算的CompletableFuture
CompletableFuture<Integer> future1 = CompletableFuture.completedFuture(5);
CompletableFuture<Integer> future2 = future1.thenApplyAsync(result -> result * 2);
future2.thenAccept(System.out::println).join();
}
}
thenApplyAsync
方法:
- 作用:
thenApplyAsync
方法接收一个Function
作为参数,该Function
会在CompletableFuture
完成时被调用。它会使用默认的ForkJoinPool.commonPool()
线程池来异步执行这个Function
。在这个例子中,Function
将future1
的结果乘以2,并返回一个新的CompletableFuture
,这个新的CompletableFuture
在Function
执行完毕后完成,其结果就是Function
的返回值。
thenAccept
方法:
- 作用:
thenAccept
方法接收一个Consumer
作为参数,当CompletableFuture
完成时,会调用这个Consumer
。这里使用System.out::println
作为Consumer
,将future2
的结果打印出来。join
方法用于等待CompletableFuture
完成并获取结果,在这里保证thenAccept
中的操作执行完毕。