我偶然发现了一个问题,可以总结如下:为什么ExecutorService不调用UncaughtExceptionHandler?
当我手动创建线程时(即通过实例化java.lang.Thread
),UncaughtExceptionHandler
被适当调用。但是,当我使用带有ThreadFactory
的ExecutorService
时,处理程序被省略。我错过了什么?
public class ThreadStudy {
private static final int THREAD_POOL_SIZE = 1;
public static void main(String[] args) {
// create uncaught exception handler
final UncaughtExceptionHandler exceptionHandler = new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
synchronized (this) {
System.err.println("Uncaught exception in thread '" + t.getName() + "': " + e.getMessage());
}
}
};
// create thread factory
ThreadFactory threadFactory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
// System.out.println("creating pooled thread");
final Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler(exceptionHandler);
return thread;
}
};
// create Threadpool
ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE, threadFactory);
// create Runnable
Runnable runnable = new Runnable() {
@Override
public void run() {
// System.out.println("A runnable runs...");
throw new RuntimeException("Error in Runnable");
}
};
// create Callable
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// System.out.println("A callable runs...");
throw new Exception("Error in Callable");
}
};
// a) submitting Runnable to threadpool
threadPool.submit(runnable);
// b) submit Callable to threadpool
threadPool.submit(callable);
// c) create a thread for runnable manually
final Thread thread_r = new Thread(runnable, "manually-created-thread");
thread_r.setUncaughtExceptionHandler(exceptionHandler);
thread_r.start();
threadPool.shutdown();
System.out.println("Done.");
}
}
我期望:消息的三倍“未捕获异常...”
我得到:消息一次(由手动创建的线程触发)。
在Windows 7和Mac OS X 10.5上使用Java 1.6重现。
也许这项工作,对我来说这是确定它是不是一个FixedThreadPool ,但SingleThreadPool ...但你明白http://stackoverflow.com/a/44007121/8020889 – 2017-05-16 16:48:39