多线程this.getName()和Thread.currentThread().getName()

最近在看《java多线程编程核心技术》这本书,在看到currentThread()方法这节时,遇到了不懂的问题,后来查阅了一些资料,整理如下。

MyThread.java

public class MyThread extends Thread {
	public MyThread() {
		// TODO Auto-generated constructor stub
		System.out.println("MyThread--begin");
		System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
		System.out.println("this.getName()="+this.getName());
		System.out.println("MyThread---end");
	}
public void run(){
	System.out.println("run---begin");
	System.out.println("run.currentThread().getName()="+Thread.currentThread().getName());
	System.out.println("this.getName()="+this.getName());
	System.out.println("run---end");
}
}
Run.java

public class Run {
public static void main(String[] args){
	MyThread thread=new MyThread();
	Thread t1=new Thread(thread);
	t1.setName("A");
	t1.start();
}
}
结果如下:



解释:

首先要明白的一点是Thread t1=new Thread(thread),t1只是调用了thread里面的run方法而已,t1和thread是两个完全不一样的对象,在开始执行

MyThread thread=new MyThread()时会调用MyThread的构造方法。Thread.currentThread.getName()是获取当前现成的名字,构造器当中返回的自然是main,this.getName()获取的是thread对象的名字,因此是Thread-0。t1.setName("A")仅仅是改变了t1的名字,和thread对象没有关系。Thread的源代码如下:


现在把Run改成如下:

public class Run {
public static void main(String[] args){
	MyThread thread=new MyThread();
	//Thread t1=new Thread(thread);
	//t1.setName("A");
	//t1.start();
	thread.setName("B");
	thread.start();
}
}
结果如下:


这里的threa.setName()就是直接修改的本身的线程名字,因此,this.getName()也会变。但是因为在执行构造方法的时候thread线程还没有执行,所以输出this.getName()=Thread-0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值