西部晨光的原帖:
程序如下:
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 ( Thread.currentThread() == creatorThread ) {
System.out.println("Creator thread");
} else if ( Thread.currentThread() == 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();
}
}
}
请问printMsg()中的this引用的是什么?(最好讲一下原理)
个人分析:
搂主的程序中启动了两个线程,因为执行这个程序的时候使用的是:
java TwoThread,假定这个时候创建的线程是Thread1
在Thread1中派生了一个线程:
TwoThread tt = new TwoThread();
tt.start();
假定这个线程是Thread2。
由于CPU始终是单线程的,所以在运行的时候也就是Thread1和Thread2进行互相切换。
下面我们来分析上述的代码,首先来看new TowThread(),在这个方法中由于Thread2还没有创建,当前的Thread.currentThread()指的是Thread1,这个属性被传递给creatorThread,所以currentThread指向的Thread1。
接着tt.start(),CPU的在Thread1和Thread2之间调度。
从Java的线程调度机制来说,首先会将Thread1运行完成,在Thread1中运行是tt.printMsg(),所以this是指tt(也就是Thread2),而Thread.currentThread()指向的是Thread1(creatorThread),所以最开始的输出是连续十次的Creator thread;然后是连续十次的New thread。
如果我们在tt.start()后紧接着让Thread1睡眠,这个时候Thread2将运行,这个时候的this仍然指向的是tt(Thread2),而Thread.currentThread()也是指向Thread2,所以结果和上面相反。
tt.start();
try
{
sleep(1000);
}
catch(Exception ex)
{}
for ( int i = 0; i < 10; i++ )
{
tt.printMsg();
}