MST

星途 面试题库

面试题:Java 中 CompletableFuture 异步任务回调参数处理之基础应用

请描述在 Java 中使用 CompletableFuture 进行异步任务,并在任务完成后获取结果并处理的基本步骤。例如,假设有一个异步任务返回一个整数,在任务完成后,将该整数乘以 2 并返回最终结果,用代码示例说明。
32.5万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 创建异步任务:使用 CompletableFuture.supplyAsync 方法创建一个异步任务,该方法接受一个 Supplier 作为参数,Supplier 中定义异步执行的逻辑。
  2. 处理任务结果:使用 thenApply 方法,该方法接受一个 Function 作为参数,在异步任务完成后,将任务的返回结果作为 Function 的输入,进行进一步的处理。

以下是代码示例:

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            // 模拟异步任务,这里返回一个整数
            return 5;
        });

        CompletableFuture<Integer> resultFuture = future.thenApply(num -> num * 2);

        resultFuture.thenAccept(System.out::println).join();
    }
}

在上述代码中:

  • CompletableFuture.supplyAsync(() -> 5) 创建了一个异步任务,返回一个 CompletableFuture<Integer>,这个异步任务返回整数 5
  • future.thenApply(num -> num * 2) 对异步任务返回的结果进行处理,将其乘以 2
  • resultFuture.thenAccept(System.out::println).join() 等待异步任务完成并打印最终结果。thenAccept 方法用于消费最终结果,join 方法用于等待 CompletableFuture 完成。