MST

星途 面试题库

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

请阐述Java中CompletableFuture的whenComplete方法的作用,并编写一段代码示例展示如何使用该方法来监控任务的完成状态,包括正常完成和异常情况。
39.8万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

CompletableFuture的whenComplete方法的作用

whenComplete 方法用于在 CompletableFuture 完成(无论是正常完成还是异常完成)时执行一个回调函数。它接收两个参数,第一个参数是 CompletableFuture 正常完成时的结果,第二个参数是导致 CompletableFuture 异常完成的 Throwable。如果 CompletableFuture 正常完成,Throwable 参数为 null;如果发生异常,结果参数为 null

代码示例

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

public class CompletableFutureExample {
    public static void main(String[] args) {
        // 模拟一个异步任务
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            // 模拟一些耗时操作
            if (Math.random() > 0.5) {
                throw new RuntimeException("任务执行异常");
            }
            return "任务正常完成";
        });

        future.whenComplete((result, ex) -> {
            if (ex == null) {
                System.out.println("任务正常完成,结果是: " + result);
            } else {
                System.out.println("任务执行异常: " + ex.getMessage());
            }
        });

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

在上述代码中:

  1. 使用 CompletableFuture.supplyAsync 创建一个异步任务,该任务以随机方式决定是否抛出异常。
  2. 使用 whenComplete 方法注册一个回调函数,在任务完成时执行。回调函数根据 ex 是否为 null 来判断任务是正常完成还是异常完成,并打印相应信息。
  3. 主线程使用 Thread.sleep 防止主线程过早退出,确保异步任务有足够时间执行。