【发布时间】:2010-12-22 18:35:15
【问题描述】:
我偶然发现了一个问题,可以总结如下:
当我手动创建线程(即通过实例化java.lang.Thread)时,UncaughtExceptionHandler 会被适当地调用。但是,当我使用 ExecutorService 和 ThreadFactory 时,处理程序会被省略。我错过了什么?
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……但你明白了stackoverflow.com/a/44007121/8020889
标签: java multithreading