对于一个线程,我通过下面的代码段捕获了uncaught exception
。但是,对于ExecutorService executor = Executors.newFixedThreadPool(10);
,如何捕获未捕获的异常?
Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
System.out.println("Uncaught exception: " + ex);
}
};
您可以使用方法newFixedThreadPool
的重载,该方法接受ThreadFactory
:
Thread.UncaughtExceptionHandler eh = ...;
ThreadFactory factory = r -> {
Thread t = new Thread(r);
t.setUncaughtExceptionHandler(eh);
return t;
};
ExecutorService executor = Executors.newFixedThreadPool(10, factory);
添加到以上答案中,您可以使用Executors defaultThreadFactory并添加自己的uncaughtExceptionHandler。它将更好地管理线程。
ExecutorService executorService = Executors.newFixedThreadPool(10, runnable -> {
Thread t = Executors.defaultThreadFactory().newThread(runnable);
t.setUncaughtExceptionHandler((Thread th, Throwable e) -> {e.printStackTrace();});
return t;
});