關於Thread.currentThread()和this的差別

從新來看多線程時,被這結果搞懵逼了。很少說,直接上代碼:緩存

 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
View Code
解析:
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;
相關文章
相關標籤/搜索