MST

星途 面试题库

面试题:Java的Executor框架中如何处理任务执行异常

在使用Executor框架提交任务执行时,若任务执行过程中抛出异常,有哪些方式可以捕获和处理这些异常?请结合代码示例说明。
32.4万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

在使用Executor框架提交任务执行时,捕获和处理任务执行过程中抛出异常的方式有以下几种:

使用Future获取异常

通过ExecutorService.submit方法返回的Future对象,调用get方法获取任务执行结果时,如果任务执行抛出异常,get方法会将异常重新抛出,从而可以捕获并处理。

import java.util.concurrent.*;

public class ExecutorExceptionHandling {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<Integer> future = executorService.submit(() -> {
            if (Math.random() > 0.5) {
                throw new RuntimeException("模拟异常");
            }
            return 42;
        });

        try {
            Integer result = future.get();
            System.out.println("任务执行结果: " + result);
        } catch (InterruptedException | ExecutionException e) {
            System.out.println("捕获到异常: " + e.getCause());
        } finally {
            executorService.shutdown();
        }
    }
}

使用UncaughtExceptionHandler

为线程池中的线程设置UncaughtExceptionHandler,当任务抛出未捕获的异常时,该处理器会被调用。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class ExecutorExceptionHandling2 {
    public static void main(String[] args) {
        ThreadFactory threadFactory = r -> {
            Thread t = new Thread(r);
            t.setUncaughtExceptionHandler((thread, throwable) -> {
                System.out.println("线程 " + thread.getName() + " 抛出异常: " + throwable);
            });
            return t;
        };

        ExecutorService executorService = Executors.newSingleThreadExecutor(threadFactory);
        executorService.submit(() -> {
            throw new RuntimeException("模拟异常");
        });

        executorService.shutdown();
    }
}

使用CompletableFuture处理异常

CompletableFuture提供了丰富的异常处理方法,如exceptionallyhandle等。

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

public class ExecutorExceptionHandling3 {
    public static void main(String[] args) {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            if (Math.random() > 0.5) {
                throw new RuntimeException("模拟异常");
            }
            return 42;
        });

        future.exceptionally(ex -> {
            System.out.println("捕获到异常: " + ex);
            return -1;
        }).thenAccept(result -> System.out.println("任务执行结果: " + result));

        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}