1
我的消費者沒有按照我期望的方式工作。以下是我的真實計劃中發生的一件sscce。UncaughtExceptionHandler行爲異常,然後凍結
- 預計:
- 打印
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!");
}
}
}
爲什麼它會掛起? – durron597
由於您尚未關閉執行程序服務@ durron597而導致掛起。 – Gray
你可能應該使用'Callable',一旦你調用future.get()就會拋出NPE。 – Gray