MST
星途 面试题库

面试题:Java中CompletableFuture thenCompose方法的基本使用

请简述Java中CompletableFuture的thenCompose方法的作用,并通过代码示例展示如何使用该方法将两个异步任务解耦并顺序执行,假设第一个异步任务返回一个整数,第二个异步任务根据这个整数进行一些计算并返回结果。
39.5万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

thenCompose方法的作用

thenCompose方法用于将两个异步任务解耦并顺序执行。它接收一个函数作为参数,该函数的输入是第一个异步任务的结果,输出是另一个CompletableFuturethenCompose会等待第一个CompletableFuture完成,然后使用其结果调用传入的函数,返回的新CompletableFuture将成为最终的结果。这样可以避免嵌套的CompletableFuture,使代码更简洁,结构更清晰。

代码示例

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 第一个异步任务
        CompletableFuture<Integer> task1 = CompletableFuture.supplyAsync(() -> {
            // 模拟一些耗时操作
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 5;
        });

        // 使用thenCompose将两个异步任务顺序执行
        CompletableFuture<Integer> task2 = task1.thenCompose(result -> CompletableFuture.supplyAsync(() -> {
            // 基于第一个任务的结果进行计算
            return result * 2;
        }));

        // 获取最终结果
        Integer finalResult = task2.get();
        System.out.println("最终结果: " + finalResult);
    }
}

在上述代码中:

  1. task1是第一个异步任务,它模拟了一个耗时操作并返回整数5
  2. task2使用thenCompose方法,接收task1的结果,并基于这个结果进行计算(乘以2),返回新的CompletableFuture
  3. 最后通过task2.get()获取最终计算结果并打印。