有哪位高手能给解释下下面程序里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();
}
}
}
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();
}
}
}
解决方案 »
- 点击按钮,出发处理事件,但是界面没有反应
- 请问一个多线程的JAVA程序,有几个进程?
- java web start学习
- StyledDocument的Paragraph如何解释?
- 请教关于java调试信息的输出
- 大家都來猜猜看....................
- 请问在jbuilder8中如何实现与sql server2k地连接,2k的驱动我有
- 大家在软件公司每天都干些什么呀?是不是整天都coding?有周末吗?
- ftpClient.put(d:\xx.doc)?
- 关于linux上tar包的问题
- 看深入浅出的设计模式里发现一个 具体类implement了接口却没有实现抽象方法的错误
- i++的?
此时有线程main(代号),TwoThread tt = new TwoThread(); //这里new TwoThread对象,进入其构造方法,creatorThread = Thread.currentThread(); //这里的creatorThread引用指向了当前线程,即线程main
而printMsg里的this是指向自己的引用,而这个自己就是被main线程 new 出来的TwoThread对象。这个程序的结果应该是输出10次Creator thread
和10次New thread。这就说明问题了 。