面试题答案
一键面试在使用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
提供了丰富的异常处理方法,如exceptionally
、handle
等。
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();
}
}
}