重新來看多線程時,被這結果搞懵逼了。不多說,直接上代碼:
1 public class MyThread02 extends Thread { 2 public MyThread02() { 3 System.out.println("init curr: " + Thread.currentThread().getName()); 4 System.out.println("init this: "+this.getName()); 5 } 6 @Override 7 public void run() { 8 System.out.println("run curr: " + Thread.currentThread().getName()); 9 System.out.println("run this: "+this.getName()); 10 } 11 }
1 public class Test02 { 2 public static void main(String[] args) { 3 MyThread02 target = new MyThread02(); 4 Thread thread = new Thread(target); 5 thread.setName("A"); 6 thread.start(); 7 } 8 }
Result:

1 init curr: main 2 init this: Thread-0 3 run curr: A 4 run this: Thread-0
解析:
row 123的結果很明顯,因為
Thread.currentThread()是當前代碼段正在那個線程調用,MyThread02的構造函數是有main主線程調用的,run是由thread線程調用。同時線程的默認名稱是Thread-(No),這點可以有Thread類的構造函數看出。其中一個構造函數如下:
1 public Thread(Runnable target) { 2 init(null, target, "Thread-" + nextThreadNum(), 0); 3 }
1 /* For autonumbering anonymous threads. */ 2 private static int threadInitNumber; 3 private static synchronized int nextThreadNum() { 4 return threadInitNumber++; 5 }
重點也就是最后一個this.getName() 為什么是Thread-0?
由上面的Thread構造函數可以看出當使用一個Runnable對象作為參數去實例化一個Thread對象時,實現Runable的線程類被緩存進了target對象,而當調用run()方法時,Thread類是這樣實現的,
1 public void run() { 2 if (target != null) { 3 target.run(); 4 } 5 }
由target進行調用,所以
this引用的是target,故this.getName() 為target.getName() -->Thread-0;