Catch exception for Executor, thread pool

让人想犯罪 __ 提交于 2019-12-13 03:07:15

问题


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);
    }
};

回答1:


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);


来源:https://stackoverflow.com/questions/24105323/catch-exception-for-executor-thread-pool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!