我的消费者没有按照我期望的方式工作。下面是在我的真实程序中发生的事情。
- 预期的:
- 打印
In finally!
- 打印
About to print stacktrace
- 打印
NullPointerException
堆栈跟踪。
- 打印
- 实际的:
- 打印
In finally!
- 挂,在
sun.misc.Unsafe
- 打印
程序:
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class ThreadTest implements Runnable {
public static void main(String... args) {
ExecutorService service = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread newThread = new Thread(r);
newThread.setUncaughtExceptionHandler(new MyExceptionHandler());
return newThread;
}
});
service.submit(new ThreadTest());
}
private static class MyExceptionHandler implements UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("About to print stacktrace");
e.printStackTrace();
}
}
@Override
public void run() {
Object foo = null;
try {
while(!Thread.interrupted()) {
Thread.sleep(1000);
System.out.println(foo.toString());
System.out.println("After npe!");
}
} catch(InterruptedException e) {
} finally {
System.out.println("In finally!");
}
}
}