我正在尝试使用 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 抛出异常。有什么线索吗?
谢谢!
原文由 Tom 发布,翻译遵循 CC BY-SA 4.0 许可协议
从 文档:
当你提交一个 Runnable 时,它会被包裹在一个 Future 中。
你的 afterExecute 应该是这样的: