每一个非静态方法都会有this
这个隐含的表示自身这个Object上例就是表示Thread2_4这个线程对象了!
这个隐含的表示自身这个Object上例就是表示Thread2_4这个线程对象了!
解决方案 »
- js跳转问题?
- 有关RDF的问题,谢谢
- hibernate懒加载异常
- [JSP] 高分 求struts入门实例
- 使用logic:iterate生成表单提交后取不到值,在线等待
- 高手帮帮我啊,csdn上都解决不了的问题,在别处更解决不了啊.(送100分 问题解决马上结贴)
- 如何在网页中取得登陆人的IP地址(JAVA)
- jsp 保存excel 问题!
- tomcat启动报这个异常,坐等大神解答
- 急!!我的页面提交不了用jsp???????
- struts错误: Cannot find ActionMappings or ActionFormBeans collection
- 哪儿有weblogic的学习资料下载啊???
import java.io.*;
import java.lang.*;public class Thread2_4 extends Thread
{
private Thread creatorThread; public Thread2_4()
{
//此处是将主线程存储起来了。
creatorThread = Thread.currentThread(); } public void run()
{
for ( int i = 0; i < 10; i++ )
{
//此处换成下面这样
//System.out.println(Thread.currentThread());
//可以看到,是新的线程在执行。
System.out.println("New thread");
}
} public void printMsg()
{
//此处还是主线程在调用这个方法,所以t还是主线程。
Thread t = Thread.currentThread();
//此处两个变量都存储着主线程。
if (t == creatorThread)
{
System.out.println("Creator thread");
}
else if (t == this) // this不是主线程?
{
System.out.println("New Thread");
}
else
{
System.out.println("Mystery thread - unexpected");
}
} public static void main(String[] args)
{
Thread2_4 tt = new Thread2_4();//此处对应第一处注释。
tt.start(); for ( int i = 0; i < 10; i++ )
{
//是主线程在调用,所以Thread.currentThread()会返回主线程。
tt.printMsg(); }
}
}
//你明白了吗?
tt.printMsg()执行后进入printMsg()函数,该函数内部的this应该是new Thread2_4()的引用,我没说错吧?
==============================================
import java.io.*;
import java.lang.*;public class Thread2_4 extends Thread
{
private Thread creatorThread; public Thread2_4()
{
creatorThread = Thread.currentThread();
} public void run()
{
for ( int i = 0; i < 10; i++ )
{
printMsg();
}
} public void printMsg()
{
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)
{
Thread2_4 tt = new Thread2_4();
tt.start(); for ( int i = 0; i < 10; i++ )
{
tt.printMsg();
}
}
}
然后你要疑问为什么到了System.out.println("Mystery thread - unexpected");
这里了?
注意 == 和equals的区别!
因为在run方法中执行printMsg(),t==this为真,t是Thread2_4的
在main中执行printMsg(),t==creatorThread为真,t是主线程的!
所以是这样的!
谁呀!?不告诉我??说,你的新男朋友是谁??
反正不是你!
你给我带green hat!我终于可以成立www.greenhat.org,可以和那个redhat.org竞争了!
哈哈!我还可以成立www.pitiao.com!~
printMsg()函数如果是主线程调用的那Thread.currentThread()就返回主线程。如果是其它线程调用就返回其它线程呗。
另外,你的程序做比较时,最好用.equals()来做。
Thread t = Thread.currentThread()后,
t可以是t == creatorThread,
又可以是t == this呢?
运行时的线程相同,也就是main,而this则是对象本身在这里是thread2_4了