捕获执行器异常,线程池 [英] Catch exception for Executor, thread pool
本文介绍了捕获执行器异常,线程池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于一个线程,我通过以下代码段捕获了未捕获的异常
。但是,对于 ExecutorService executor = Executors.newFixedThreadPool(10);
,如何捕获未捕获的异常?
For one thread, I catch the uncaught exception
via below code segments. However, for ExecutorService executor = Executors.newFixedThreadPool(10);
, how can I catch uncaught exception?
Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
System.out.println("Uncaught exception: " + ex);
}
};
推荐答案
您可以使用方法<$ c的重载$ c> newFixedThreadPool ,它接受 ThreadFactory
:
You can use the overload of the method newFixedThreadPool
, which accepts a ThreadFactory
:
Thread.UncaughtExceptionHandler eh = ...;
ThreadFactory factory = r -> {
Thread t = new Thread(r);
t.setUncaughtExceptionHandler(eh);
return t;
};
ExecutorService executor = Executors.newFixedThreadPool(10, factory);
这篇关于捕获执行器异常,线程池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文