MST
星途 面试题库

面试题:Java中supplyAsync方法的异常处理与线程池应用

在使用CompletableFuture的supplyAsync方法时,如果异步任务抛出异常,如何优雅地进行处理?请举例说明。另外,如果想要使用自定义的线程池来执行supplyAsync方法中的任务,该如何操作?请编写相应代码。
10.4万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 处理异步任务抛出的异常
    • 使用exceptionally方法来优雅处理异常。exceptionally方法会在异步任务抛出异常时被调用,它接收一个Function,这个Function的参数是异常,返回值是当异常发生时要返回的替代结果。
    • 示例代码如下:
import java.util.concurrent.CompletableFuture;

public class CompletableFutureExceptionHandling {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> {
            if (Math.random() > 0.5) {
                throw new RuntimeException("模拟异常");
            }
            return "任务正常完成";
        }).exceptionally(ex -> {
            System.out.println("捕获到异常: " + ex.getMessage());
            return "异常替代结果";
        }).thenAccept(System.out::println);
    }
}
  1. 使用自定义线程池执行supplyAsync方法中的任务
    • 首先创建一个ExecutorService线程池,然后将其作为参数传递给supplyAsync方法。
    • 示例代码如下:
import java.util.concurrent.*;

public class CompletableFutureCustomThreadPool {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        CompletableFuture.supplyAsync(() -> {
            System.out.println("任务在自定义线程池中执行");
            return "任务执行结果";
        }, executor).thenAccept(System.out::println).whenComplete((result, ex) -> {
            executor.shutdown();
        });
    }
}