实现思路
- 自定义异常处理类:实现
Thread.UncaughtExceptionHandler
接口,在 uncaughtException
方法中记录异常日志,并根据异常类型进行不同处理。
- 设置线程池的异常处理策略:创建线程池时,使用
ThreadPoolExecutor
的构造函数,设置 ThreadFactory
,在 ThreadFactory
中为每个线程设置自定义的异常处理类。
关键代码片段
import java.util.concurrent.*;
// 自定义异常处理类
class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
// 记录异常日志
System.err.println("Thread " + t.getName() + " threw an exception: " + e.getMessage());
// 根据异常类型进行不同处理
if (e instanceof SpecificException) {
// 对于特定异常进行重试操作
System.err.println("Retrying due to SpecificException...");
// 这里添加重试逻辑
} else {
// 其他异常处理
System.err.println("Handling other exception...");
}
}
}
// 特定异常类
class SpecificException extends RuntimeException {
public SpecificException(String message) {
super(message);
}
}
// 自定义ThreadFactory
class CustomThreadFactory implements ThreadFactory {
private final UncaughtExceptionHandler handler;
public CustomThreadFactory(UncaughtExceptionHandler handler) {
this.handler = handler;
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setUncaughtExceptionHandler(handler);
return t;
}
}
public class ThreadPoolExceptionHandling {
public static void main(String[] args) {
CustomExceptionHandler handler = new CustomExceptionHandler();
CustomThreadFactory factory = new CustomThreadFactory(handler);
// 创建线程池并设置自定义ThreadFactory
ThreadPoolExecutor executor = new ThreadPoolExecutor(
2, // corePoolSize
4, // maximumPoolSize
10, TimeUnit.SECONDS, // keepAliveTime
new LinkedBlockingQueue<>(),
factory);
// 提交任务
executor.submit(() -> {
throw new SpecificException("Specific exception occurred");
});
// 关闭线程池
executor.shutdown();
}
}