多线程中this.getName()和Thread.currentThread().getName()返回名字不一样的问题

来源:互联网 发布:bt29万能钥匙下载软件 编辑:程序博客网 时间:2024/05/17 22:05
public class hello extends Thread {  
public hello(){
System.out.println("Thread.currentThread().getname()="+Thread.currentThread().getName());
System.out.println("This.getName="+this.getName());
}
public void run(){
System.out.println("Thread.currentThread().getname()="+Thread.currentThread().getName());
System.out.println("This.getName="+this.getName());
}
    public static void main(String[] args){
     hello thread =new hello();
     Thread t1 =new Thread(thread);
     t1.setName("A");
     t1.start();
  }
    }
得到结果
Thread.currentThread().getname()=main
This.getName=Thread-0
Thread.currentThread().getname()=A

This.getName=Thread-0


解释:

首先要清楚thread和t1是两个完全不同的对象,他俩之间唯一的关系就是把thread传递给t1对象,仅仅是为了让t1调用thread对象的run方法。

hello thread = new hello();运行这句话的时候会调用hello的构造方法,Thread.currentThread().getName()是获得调用这个方法的线程的名字,在main线程中调用的当然是main了,而this.getName()这个方法是获取当前hello对象的名字(this代表的是thread这个对象),只是单纯的方法的调用。因为没有重写这个方法所以调用的是父类Thread(把这个对象当作是普通的对象)中的方法。

this.getName()-->public final String getName() {return String.valueOf(name);    }-->所以最终是输出name的值,因为你在hello的构造方法中没有显式调用父类的所以调用的是默认无参的public Thread() {init(null, null, "Thread-" + nextThreadNum(), 0);    }-->最终的名字就是这个"Thread-" + nextThreadNum()-->private static synchronized int nextThreadNum() {return threadInitNumber++;    }-->private static int threadInitNumber;因为是第一次调用nextThreadNum() 方法所以返回值为0-->this.getName()=Thread-0

后面的输出类似。t1.setName("A");这句话只是修改了t1的名字,和thread对象没有关系,所以run方法中this.getName()的输出还是Thread-0。

currentThread()方法返回的是对当前正在执行的线程对象的引用,this代表的是当前调用它所在函数所属的对象的引用


0 0