我正在尝试使用Java的ThreadPoolExecutor类来运行大量重量级任务,使用固定数量的线程。每个任务都有许多可能由于异常而失败的地方。
我已经创建了ThreadPoolExecutor的子类,并覆盖了afterExecute方法,该方法应提供在运行任务时遇到的任何未捕获异常。然而,我似乎无法使其起作用。
例如:
这个程序的输出是“一切都好 - 情况正常!”,即使提交给线程池的唯一可运行对象抛出异常。这是怎么回事呢?谢谢!
我已经创建了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();
}
}
这个程序的输出是“一切都好 - 情况正常!”,即使提交给线程池的唯一可运行对象抛出异常。这是怎么回事呢?谢谢!