Executor的捕获异常,线程池

问题描述 投票:0回答:2

对于一个线程,我通过下面的代码段捕获了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);
    }
};
java multithreading exception-handling jvm
2个回答
1
投票

您可以使用方法newFixedThreadPool的重载,该方法接受ThreadFactory

Thread.UncaughtExceptionHandler eh = ...;
ThreadFactory factory = r -> {
    Thread t = new Thread(r);
    t.setUncaughtExceptionHandler(eh);
    return t;
};
ExecutorService executor = Executors.newFixedThreadPool(10, factory);

0
投票

添加到以上答案中,您可以使用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;
    });
© www.soinside.com 2019 - 2024. All rights reserved.