MST
星途 面试题库

面试题:Java中CompletableFuture的thenAcceptAsync方法基础应用

请编写一段Java代码,使用CompletableFuture的thenAcceptAsync方法实现一个异步任务,主线程提交一个计算任务(例如计算两个数之和),当任务完成后,异步打印出计算结果。同时,请解释thenAcceptAsync方法的参数含义及作用。
18.0万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> {
            int num1 = 5;
            int num2 = 3;
            return num1 + num2;
        })
       .thenAcceptAsync(result -> {
            System.out.println("计算结果为: " + result);
        });

        // 防止主线程结束
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

thenAcceptAsync方法参数含义及作用

  • thenAcceptAsync方法接受一个Consumer类型的参数,在上述代码中,result -> System.out.println("计算结果为: " + result)就是这个Consumer。它的作用是当CompletableFuture异步任务完成时,对任务的结果进行处理。在这里,它会异步地打印出计算结果。thenAcceptAsync方法会使用默认的ForkJoinPool.commonPool()线程池来执行这个Consumer,从而实现异步处理结果的功能。如果需要指定线程池,可以使用thenAcceptAsync(Consumer<? super U> action, Executor executor)这个重载方法,其中executor就是你指定的线程池。