public class Hello extends Thread {
public Hello(String name) {
super(name);
System.out.println("構造器: currentThread=" + Thread.currentThread().getName()
+ ", this.getName=" + this.getName());
}
public void run() {
System.out.println("run: currentThread=" + Thread.currentThread().getName()
+ ", this.getName=" + this.getName());
}
public static void main(String[] args) {
Thread t1 = new Thread(new Hello("A"));
t1.setName("B");
t1.start();
}
}
輸出:
構造器: currentThread=main, this.getName=A run: currentThread=B, this.getName=A
| 表達式 | 代表對象 | 說明 |
|---|---|---|
this | `Hello` 實例(繼承 `Thread` 的任務對象) | 調用 `getName()` 返回構造器傳入的 "A" |
Thread.currentThread() | 正在執行代碼的線程實例 | 構造器由 main 線程調用 → main;`run()` 由新線程 t1 執行 → B |
Thread 實例 ≠ 執行線程。`new Thread(runnable)` 創建的是線程控制對象,`runnable` 是任務載體。