有哪位高手能给解释下下面程序里printMsg() 方法里的t == creatorThread 和 t == this 有啥区别public class TwoThread extends Thread {
private Thread creatorThread; public TwoThread() {
// make a note of the thread that constructed me!
creatorThread = Thread.currentThread();
} public void run() {
for ( int i = 0; i < 10; i++ ) {
printMsg();
}
} public void printMsg() {
// get a reference to the thread running this
Thread t = Thread.currentThread(); if ( t == creatorThread ) {
System.out.println("Creator thread");
} else if ( t == this ) {
System.out.println("New thread");
} else {
System.out.println("Mystery thread --unexpected!");
}
} public static void main(String[] args) {
TwoThread tt = new TwoThread();
tt.start(); for ( int i = 0; i < 10; i++ ) {
tt.printMsg();
}
}
}

解决方案 »

  1.   

    从main方法进入程序开始执行,
    此时有线程main(代号),TwoThread tt = new TwoThread(); //这里new TwoThread对象,进入其构造方法,creatorThread = Thread.currentThread(); //这里的creatorThread引用指向了当前线程,即线程main
    而printMsg里的this是指向自己的引用,而这个自己就是被main线程 new 出来的TwoThread对象。这个程序的结果应该是输出10次Creator thread
    和10次New thread。这就说明问题了 。