代碼如下:public class ThreadTest extends Thread{ public ThreadTest() { System.out.println("構造方法a:" + Thread.currentThread().getName()); System.out.println("構造方法b:" + this.getName()); } @Override public void run() { System.out.println("run方法a:" + Thread.currentThread().getName()); System.out.println("run方法b:" + this.getName()); } public static void main(String[] args) { Thread thread = new ThreadTest(); thread.setName("thread"); thread.start(); } }運行結果:構造方法a:main構造方法b:Thread-0run方法a:threadrun方法b:thread問題:1、構造方法中的this.getName()方法的返回值怎么得出來的?2、run()方法里的this是否指代當前運行的線程?3、Thread.currentThread()方法返回的是當前正在運行的線程嗎?新手求指點,多謝?。?!
4 回答

瀟瀟雨雨
TA貢獻1833條經驗 獲得超4個贊
Thread.currentThread()不是返回當前程序運行的線程,而是返回Thread.currentThread()這句代碼執(zhí)行時所在的線程。
所以看到,新的分線程構造時代碼在主線程中執(zhí)行,而run方法內的代碼是分線程中執(zhí)行的。
看輸出很容易理解

慕村9548890
TA貢獻1884條經驗 獲得超4個贊
1、new
一個Thread
對象的時候默認的名字就是Thread-n
格式的,你可以看看Thread
源碼。
2、你這就是一個線程對象,this
在你這樣使用的情況下,是當前的線程了。
3、Thread.currentThread()
永遠都是返回當前運行的線程。
添加回答
舉報
0/150
提交
取消