我正在尝试使用 Java 的ThreadPoolExecutor
类来运行具有固定数量线程的大量重量级任务。每个任务都有很多地方可能由于异常而失败。
我已经子类ThreadPoolExecutor
化并且我已经覆盖了afterExecute
应该提供运行任务时遇到的任何未捕获异常的方法。但是,我似乎无法让它工作。
例如:
public class ThreadPoolErrors extends ThreadPoolExecutor {
public ThreadPoolErrors() {
super( 1, // core threads
1, // max threads
1, // timeout
TimeUnit.MINUTES, // timeout units
new LinkedBlockingQueue<Runnable>() // work queue
);
}
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if(t != null) {
System.out.println("Got an error: " + t);
} else {
System.out.println("Everything's fine--situation normal!");
}
}
public static void main( String [] args) {
ThreadPoolErrors threadPool = new ThreadPoolErrors();
threadPool.submit(
new Runnable() {
public void run() {
throw new RuntimeException("Ouch! Got an error.");
}
}
);
threadPool.shutdown();
}
}
该程序的输出是“一切正常——情况正常!” 即使提交给线程池的唯一 Runnable 抛出异常。有什么线索吗?
谢谢!