捕获Executor,线程池的异常

时间:2014-06-08 10:42:19

标签: java multithreading exception-handling jvm

对于一个帖子,我通过以下代码段捕获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);
    }
};

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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;
    });