A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© saiqqww234 中级黑马   /  2016-5-2 18:04  /  399 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

import java.util.concurrent.*;

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);
}
}

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;
}
}

public class CaptureUncaughtException {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool(
new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
}
}

chapter21.chapter21_1.HandlerThreadFactory@6d6f6e28 creating new Thread
created Thread[Thread-0,5,main]
eh = chapter21.chapter21_1.MyUncaughtExceptionHandler@135fbaa4
run() by Thread[Thread-0,5,main]
eh = chapter21.chapter21_1.MyUncaughtExceptionHandler@135fbaa4
chapter21.chapter21_1.HandlerThreadFactory@6d6f6e28 creating new Thread
created Thread[Thread-1,5,main]
eh = chapter21.chapter21_1.MyUncaughtExceptionHandler@7c5085ec
caught java.lang.RuntimeException

看输出结果是创建了两个线程,但明明只有一个exec.execute(new ExceptionThread2());为什么会创建两个线程?当输出caught java.lang.RuntimeException后程序并没有退出,而是一直在运行状态,但也没有任何输出,只能手动关闭,为什么?

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马