【Java多線程與併發】——Thread.currentThread().getName()和this.getName()區別

首先,Thread.currentThread().getName() 和 this.getName()都可以用來獲得線程的名稱,但是它們是有區別滴,不能亂用!

下面分別對這兩個方法進行剖析:

先來說說currentThread()方法,它的源碼如下,它是一個本地方法,方法返回一個Thread對象:
 

 /**
     * Returns a reference to the currently executing thread object.
     *
     * @return  the currently executing thread.
     */ public static native Thread currentThread();

接下來看看 getName()方法,它是Thread類中的一個方法(並不是Object類中的方法),源碼如下:

 /**
     * Returns this thread's name.
     *
     * @return  this thread's name.
     * @see     #setName(String)
     */ public final String getName() { return String.valueOf(name); }

其中,name是Thread類中的一個域,是char[],getName()方法可以返回當前線程的名稱。

所以我們可以總結:Thread.currentThread().getName()可以在任何情況下使用;而this.getName()必須在Thread類的子類中使用,this指代的必須是Thread對象!

爲了更好的說明兩者的差別,可以看以下代碼:

public class MyThread extends Thread {
    public MyThread() {
        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.......");
        System.out.println();
    }

    @Override
    public void run() {
        System.out.println(".....run begin.....");
        System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
        System.out.println("this.getName() = " + this.getName());
        System.out.println(".....run end.......");
    }
}
    public class MyThreadTest {
        public static void main(String[] args) { // TODO Auto-generated method stub 
             MyThread mt = new MyThread();
             Thread t = new Thread(mt);
             t.setName("A"); t.start(); 
        } 
    }

輸出結果爲:

其中,Thread.currentThread().getName()調用的是執行此行代碼的線程的getName方法;this.getName()調用的是mt對象的getName方法。區別顯著有木有!!!

這裏比較讓人疑惑的是“this.getName() = Thread-0”,這個Thread-0是什麼鬼???
通過查看Thread源碼發現,在Thread類的構造方法中,會自動給name賦值,賦值代碼:
 

"Thread-" + nextThreadNum()

 有興趣的同學可以自己去查源碼!
這就解釋了爲什麼“this.getName() = Thread-0”。

其中,Thread.currentThread().getName()調用的是執行此行代碼的線程的getName方法;this.getName()調用的是mt對象的getName方法。區別顯著有木有!!!
---------------------
作者:wozhuhonghao
來源:CSDN
原文:https://blog.csdn.net/u012665227/article/details/50242655
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章