admin管理员组文章数量:1612099
最近在看java多线程编程核心技术这本书,由于一直对于线程的应用和学习不深,在例子中碰到Thread.currentThread().getName() 和 this.getName()的问题很困惑,刚弄懂分享下,有不对的地方还请多多指教。
public class MyThread extends Thread {
public MyThread(){
System.out.println("---MyThread begin---");
System.out.println("Thread.currentThread.getName()=" +Thread.currentThread().getName());
System.out.println("this.getName()=" + this.getName());
System.out.println(Thread.currentThread() == this);
System.out.println("---MyThread begin---");
}
@Override
public void run(){
System.out.println("---run begin---");
System.out.println("Thread.currentThread.getName()=" +Thread.currentThread().getName());
System.out.println("this.getName()=" +this.getName());
System.out.println(Thread.currentThread() == this);
System.out.println("---run end ---");
}
public static void main(String[] args) throws InterruptedException {
MyThread tt = new MyThread();
Thread t1 = new Thread(tt);
t1.setName("test");
t1.start();
}
}
---MyThread begin---
Thread.currentThread.getName()=main
this.getName()=Thread-0
false
---MyThread begin---
---run begin---
Thread.currentThread.getName()=test
this.getName()=Thread-0
false
---run end ---
根据打印的日志可以知道调用MyThread构造函数的是main线程,因此打印出
Thread.currentThread().getName()=main
Thread.currentThread().isAlive()=true
而此时还没有启动MyThread子线程,所以打印出
this.getName=Thread-0
this.isAlive()=false
此时this代表的是MyThread对象实例,所以
Thread.currentThread()==this :false
这里比较让人疑惑的是this.getName() = Thread-0
通过查看Thread源码发现,在Thread类的构造方法中,默认会自动给name赋值:
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
在Thread源码中实际上new Thread(tt)会将tt应用的对象绑定到一个private变量target上,
在t1被执行的时候即t1.run()被调用的时候,它会调用target.run()方法,也就是说它是直接调用tt对象的run方法,也就是说,在run方法被执行的时候,this.getName()实际上返回的是target.getName(),而Thread.currentThread().getName()实际上是t1.getName()
修改代码直接执行MyThread的线程:
public static void main(String[] args) throws InterruptedException {
MyThread tt = new MyThread();
tt.setName("test");
tt.start();
}
---MyThread begin---
Thread.currentThread.getName()=main
this.getName()=Thread-0
false
---MyThread begin---
---run begin---
Thread.currentThread.getName()=test
this.getName()=test
true
---run end ---
此时MyThread构造方法和之前的输出保持一致,因为执行构造方法时线程还没有执行,所以输出this.getName=Thread-0 ;而run方法中MyThread线程已经执行并且可以获取到线程的名称,所以输出:
Thread.currentThread.getName()=test
this.getName()=test
本文标签: 详解区别threadcurrentThreadgetName
版权声明:本文标题:Thread.currentThread().getName() 和 this.getName()区别详解 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1728630210a1166998.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论