UncaughtExceptionHandler 打印了两遍

plugin 发布于 2017/06/28 23:39
阅读 64
收藏 0
public class CaptureUncaughtException {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
        exec.execute(new ExceptionThread2());
    }


}
class HandlerThreadFactory implements ThreadFactory {
    public Thread newThread(Runnable r) {
        System.out.println(this + " creating  new Thread.");
        Thread t = new Thread(r);
        System.out.println("created " + t);
        t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        System.out.println("eh = " + t.getUncaughtExceptionHandler());
        return t;
    }
}

class ExceptionThread2 implements Runnable {
    public void run() {
        Thread t = Thread.currentThread();
        System.out.println("run() by " + t);
        System.out.println("eh = " + t.getUncaughtExceptionHandler());
        throw new RuntimeException();
    }
}

class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("caught " + e);
    }
}
com.concurrent.uncaught.HandlerThreadFactory@287b2e39 creating  new Thread.
created Thread[Thread-0,5,main]
eh = com.concurrent.uncaught.MyUncaughtExceptionHandler@5c772046
run() by Thread[Thread-0,5,main]
eh = com.concurrent.uncaught.MyUncaughtExceptionHandler@5c772046
com.concurrent.uncaught.HandlerThreadFactory@287b2e39 creating  new Thread.
created Thread[Thread-1,5,main]
eh = com.concurrent.uncaught.MyUncaughtExceptionHandler@4c3212a8
caught java.lang.RuntimeException

 

这里的createing new Thread 加上随后的两行为什么执行了两遍呢?

加载中
返回顶部
顶部