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作為一個target傳遞給了t1,hello thread = new hello();運行這句話的時候會調用hello的構造方法,Thread.currentThread().getName()是獲得調用這個方法的線程的名字,在main線程中調用的當然是main了,而this.getName()這個方法是獲取當前hello對象的名字,只是單純的方法的調用。因為沒有重寫這個方法所以調用的是父類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。