1. 程式人生 > >JAVA中的Thread.currentThread是什麼意思

JAVA中的Thread.currentThread是什麼意思

當年學的時候,我也納悶,為什麼獲取當前執行緒需要呼叫Thread類的靜態方法去獲取,為毛不直接用物件操作就行了啊?
上程式碼先:

class MyThread extends Thread {

@Override
public void run() {
try {
Thread.sleep(500);
Thread t = Thread.currentThread();
System.out.println("當前執行緒名字:" + t.getName() + " 當前執行緒的優先級別為:"+ t.getPriority() + " ID:" + t.getId());
// System.out.println("當前執行緒名字:" + this.getName() + " 當前執行緒的優先級別為:" + this.getPriority() + " ID:"+ this.getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class TestDemo {
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt, "Name1").start();
new Thread(mt, "Name2").start();
new Thread(mt).start();
System.out.println(Thread.currentThread().getName()); // main主方法
}
}

看上面,貌似你會用Thread.currentThread()。
但是問題來了,為毛不直接用物件操作就行了啊?
把run()方法裡的Thread.currentThread() 直接替換成 this不就行了(替換成註釋掉的程式碼),直接用物件多省事啊。
不知你們學習時有沒有過這樣的疑惑,因為我確實想不到哪裡需要呼叫到這個執行緒而拿不到這個執行緒的情況。

可是新的問題又出現了,你試試看執行上面這段程式碼,this和Thread.currentThread()輸出的內容是否相同?

行比較一下吧。沒想到吧,差別明顯啊!所以題外插一句:如果呼叫isInterrupted返回true,this就是當前執行緒物件,此時
Thread.currentThread()與this表示同一物件。否則,就必須使用Thread.currentThread()獲取當前執行緒。

而且既然是使用到了多執行緒,多半情況下都不會知道系統當前執行的是哪塊執行緒,所以你需要呼叫Thread.currentThread()方法來獲取系統當前正在執行的一條執行緒,然後才可以對這個執行緒進行其他操作,就是這個意思。

https://zhidao.baidu.com/question/691200709162399644.html