文章目录
如果某个任务同时依赖另外两个异步任务的执行结果,就需要对另外两个异步任务进行合并。以泡茶喝为例,“泡茶喝”任务需要对“烧水”任务与“清洗”任务进行合并。
对两个异步任务的合并可以通过CompletionStage接口的thenCombine()、runAfterBoth()、thenAcceptBoth()三个方法来实现。
一. 合并两个异步任务的结果
1. thenCombine()
:组合两个异步任务的结果
thenCombine()
方法允许我们同时处理两个异步任务的结果。当这两个任务都完成时,它会执行一个 BiFunction
,将两个任务的结果组合起来,并返回一个新的 CompletableFuture
,该 CompletableFuture
包含组合后的结果。
使用场景:当你有两个异步任务,且需要同时使用它们的结果来进行某些操作时,thenCombine()
非常适合。
示例代码:
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 2);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 3);
future1.thenCombine(future2, (result1, result2) -> result1 + result2)
.thenAccept(result -> System.out.println(result)); // 输出 5
**分析**:
- `future1` 和 `future2` 是两个异步任务,分别返回 `2` 和 `3`。
- `thenCombine()` 会将这两个结果相加,并返回 `5`。
- `thenAccept()` 最终打印出 `5`。
例子2:
@Test
public void thenCombineDemo() throws Exception {
CompletableFuture<Integer> future1 =
CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
Integer firstStep = 10 + 10;