日期:2014-05-20  浏览次数:20888 次

有关ThreadFactory的调用问题,请教大家
在《java编程思想》上面的一个例子,但是跑完了结果很诧异,源代码如下


package concurrency;//: concurrency/CaptureUncaughtException.java
import java.util.concurrent.*;

class ExceptionThread2 implements Runnable {
    public void run() {
        Thread t = Thread.currentThread();
        System.out.println("\nrun() 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("\ncaught " + e);
    }
}

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

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


书中给出的输出应该是这样:

/* Output: (90% match)
HandlerThreadFactory@de6ced creating new Thread
created Thread[Thread-0,5,main]
eh = MyUncaughtExceptionHandler@1fb8ee3
run() by Thread[Thread-0,5,main]
eh = MyUncaughtExceptionHandler@1fb8ee3
caught java.lang.RuntimeException
*///:~

我把源代码做了一点点修改,格式上更容易看,在我机器上跑完了结果是这样:

concurrency.HandlerThreadFactory@33e2ad75 creating new Thread
created Thread[Thread-0,5,main]
factory eh = concurrency.MyUncaughtExceptionHandler@60d70b42

run() by Thread[Thread-0,5,main]
eh = concurrency.MyUncaughtExceptionHandler@60d70b42

concurrency.HandlerThreadFactory@33e2ad75 creating new Thread
created Thread[Thread-1,5,main]
factory eh = concurrency.MyUncaughtExceptionHandler@de35b38

caught java.lang.RuntimeException

很明显,ThreadFactory中的代码多执行了一遍,不解这是为什么,麻烦大家帮忙告诉一下,多谢
------解决方案--------------------
用你给的源码跑结果就是书中的,你修改源码了?改什么了?
是不是改动照成的