在CSDN社区中西部晨光关于线程中的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 ( 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();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值