关于《Thinking In Java》一书第四版并发一章的一个问题

《Thinking In Java》一书并发一章中关于捕获从线程中逃逸出的异常有这样一段代码:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

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

class ExceptionThread2 implements Runnable{

public void run() {
    // TODO Auto-generated method stub
    Thread t = Thread.currentThread();
    System.out.println("run() by " + t);
    System.out.println("eh = " + t.getUncaughtExceptionHandler());
    throw new RuntimeException();
}

}

class MyUncaughtExceptonHandler implements Thread.UncaughtExceptionHandler{

public void uncaughtException(Thread t, Throwable e) {
    // TODO Auto-generated method stub
    System.out.println("caught " + e);
}

}

class HandlerThreadFactory implements ThreadFactory{

public Thread newThread(Runnable r) {
    // TODO Auto-generated method stub
    System.out.println(this + " creating new Thread");
    Thread t = new Thread(r);
    System.out.println("created " + t);
    t.setUncaughtExceptionHandler(new MyUncaughtExceptonHandler());
    System.out.println("eh = " + t.getUncaughtExceptionHandler());
    return t;
}

}

按照代码的逻辑,运行结果应该是:
chapter_21.HandlerThreadFactory@4e25154f creating new Thread
created Thread[Thread-0,5,main]
eh = chapter_21.MyUncaughtExceptonHandler@70dea4e
run() by Thread[Thread-0,5,main]
eh = chapter_21.MyUncaughtExceptonHandler@70dea4e
caught java.lang.RuntimeException

但是我在自己的电脑上,不管是用jdk1.8还是Jdk1.7运行结果都是:
chapter_21.HandlerThreadFactory@4e25154f creating new Thread
created Thread[Thread-0,5,main]
eh = chapter_21.MyUncaughtExceptonHandler@70dea4e
run() by Thread[Thread-0,5,main]
eh = chapter_21.MyUncaughtExceptonHandler@70dea4e
chapter_21.HandlerThreadFactory@4e25154f creating new Thread
created Thread[Thread-1,5,main]
eh = chapter_21.MyUncaughtExceptonHandler@6c9ffdd2
caught java.lang.RuntimeException

HandlerThreadFactory类的newThread()方法出现了重复。我又在室友的机器上运行,而他的运行结果与预期结果相同,即没有这段重复的运行结果。这让我很疑惑,我觉得这应该与具体机器的线程调度机制有关,不知道有没有人能够帮我解答一下

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!