MST

星途 面试题库

面试题:Java CompletableFuture whenComplete方法在复杂异步任务链中的应用

假设有一系列异步任务,任务A完成后触发任务B和任务C并行执行,任务B和任务C都完成后再执行任务D。请使用CompletableFuture的whenComplete方法来实现这一流程,并处理可能出现的异常情况,说明每个环节中whenComplete方法的具体作用。
24.3万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

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

public class AsyncTaskExample {
    public static void main(String[] args) {
        CompletableFuture<Void> taskA = CompletableFuture.runAsync(() -> {
            System.out.println("Task A is running.");
            // 模拟任务A执行耗时操作
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        CompletableFuture<Void> taskB = taskA.thenRunAsync(() -> {
            System.out.println("Task B is running.");
            // 模拟任务B执行耗时操作
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        CompletableFuture<Void> taskC = taskA.thenRunAsync(() -> {
            System.out.println("Task C is running.");
            // 模拟任务C执行耗时操作
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(taskB, taskC);

        combinedFuture.whenComplete((result, exception) -> {
            if (exception != null) {
                System.out.println("An exception occurred during Task B or Task C: " + exception.getMessage());
            } else {
                System.out.println("Both Task B and Task C completed successfully. Starting Task D.");
                CompletableFuture.runAsync(() -> {
                    System.out.println("Task D is running.");
                    // 模拟任务D执行耗时操作
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }).whenComplete((res, ex) -> {
                    if (ex != null) {
                        System.out.println("An exception occurred during Task D: " + ex.getMessage());
                    } else {
                        System.out.println("Task D completed successfully.");
                    }
                });
            }
        });
    }
}

各环节whenComplete方法的具体作用

  1. combinedFuture.whenComplete
    • 作用:用于监听任务B和任务C的完成情况。当任务B和任务C都完成时,会执行这个whenComplete中的代码块。
    • 具体实现:在whenComplete的代码块中,首先检查是否有异常发生(通过exception != null判断)。如果有异常,打印出异常信息;如果没有异常,说明任务B和任务C都成功完成,然后启动任务D。
  2. 任务D中的whenComplete
    • 作用:用于监听任务D的完成情况。当任务D完成时,会执行这个whenComplete中的代码块。
    • 具体实现:同样检查是否有异常发生(通过ex != null判断)。如果有异常,打印出异常信息;如果没有异常,打印任务D成功完成的信息。