gpt4 book ai didi

java - Executor、线程池的捕获异常

转载 作者:行者123 更新时间:2023-12-01 12:52:41 29 4
gpt4 key购买 nike

对于一个线程,我通过以下代码段捕获未捕获的异常。但是,对于 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);

关于java - Executor、线程池的捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24105323/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com