MST

星途 面试题库

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

请用Java代码示例说明CompletableFuture的whenComplete方法如何使用,以及它的参数代表什么含义。要求展示一个简单的异步任务并在任务完成时通过whenComplete方法打印任务的执行结果或异常信息。
46.4万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

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

public class CompletableFutureWhenCompleteExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            // 模拟异步任务
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "异步任务执行结果";
        }).whenComplete((result, exception) -> {
            if (exception == null) {
                System.out.println("任务执行成功,结果是: " + result);
            } else {
                System.out.println("任务执行出现异常: " + exception.getMessage());
            }
        });

        // 主线程等待一会儿,确保异步任务有足够时间完成
        Thread.sleep(3000);
    }
}
  • whenComplete方法参数含义:
    • result:代表异步任务成功执行后的返回值,如果任务执行异常则为null
    • exception:代表异步任务执行过程中抛出的异常,如果任务成功执行则为null。通过这两个参数可以在异步任务完成时处理任务结果或异常情况。