currentThread()方法可以返回段正在被哪個線程調用的信息。
示例代碼:
public class Main { public static void main(String[] args) { System.out.println(Thread.currentThread().getName()); } }
結果:說明main()被名為main的線程調用。

示例代碼:
public class OneThread extends Thread { public OneThread() { System.out.println("構造方法的打印: " + Thread.currentThread().getName()); } @Override public void run() { System.out.println("run方法的打印:" + Thread.currentThread().getName()); } }
執行方法:
public class Main { public static void main(String[] args) { OneThread ot = new OneThread(); ot.start(); } }
結果:

若執行方法為:
public class Main { public static void main(String[] args) { OneThread ot = new OneThread(); ot.run();//注意此處調用的是run(),我們曾提過,調用run()相當於將run()交給其他線程來完成
} }
結果:

更復雜的示例:
public class TwoThread extends Thread { public TwoThread() { System.out.println("Count-Operate--begin"); System.out.println("Thread.currentThread().getName()= " + Thread.currentThread().getName()); System.out.println("this.getName()= " + this.getName()); System.out.println("Count-Operate--end"); } @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 Main { public static void main(String[] args) { TwoThread tt = new TwoThread(); Thread t = new Thread(tt); t.setName("A"); t.start(); } }
結果:

根據結果逆向分析:Thread.currentThread().getName()獲得的始終是主線程(也就是說由JVM創建的main線程)。
而由對象本身調用的getName()獲取的都是打開的第二個線程Thread-0,也就是執行start()方法的線程。
現在分析發現這個思考是有問題的。
Thread.currentThread().getName()獲得的始終是執行start()方法的線程(或者說是調用run()方法的線程)。
而this.getName()獲得的都是run()方法所在線程對象的名稱。
源碼地址:https://github.com/lilinzhiyu/threadLearning
如果有錯誤歡迎各位指出。
