| 維度 | 進程 | 執行緒 |
|---|---|---|
| 定義 | 執行中的程式,獨立記憶體空間 | 進程內的單一循序控制流 |
| 資源 | 獨立堆、棧、檔案描述符 | 共享進程堆/方法區,私有程式計數器、棧、區域變數 |
| 建立/切換開銷 | 大(需複製記憶體映像) | 小(輕量級進程) |
| 通訊 | IPC(管道、Socket、共享記憶體) | 直接讀寫共享變數(需同步) |
class NewThread extends Thread {
NewThread(String name) { super(name); } // 傳名稱給父類
public void run() {
for (int i=10; i>0; i--) {
System.out.println(getName() + " left: " + i);
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
System.out.println("Game over!");
}
}
public class Demo {
public static void main(String[] args) {
new NewThread("Thread-Demo").start(); // 必須呼叫 start(),不可直接呼叫 run()
}
}
關鍵點:覆寫 run()、建構子呼叫 super(name)、用 start() 啟動(非 run())。
class NewTask implements Runnable {
public void run() { /* 同樣邏輯 */ }
}
public class Demo {
public static void main(String[] args) {
Runnable task = new NewTask();
new Thread(task, "Runnable-Demo").start();
// 或 Java 8+ Lambda
new Thread(() -> { /* ... */ }, "Lambda-Demo").start();
}
}
Runnable 實例可建立多執行緒,共享資料。public static void main(String[] args) {
Thread main = Thread.currentThread(); // 取得主執行緒參考
main.setName("Main-Thread");
System.out.println(main.getName() + " started");
new Thread(() -> System.out.println("Child running")).start();
}
main()。Thread(String name) 或 setName() 設定名稱。jstack、日誌皆顯示執行緒名稱,善用命名大幅提升除錯效率。t.run() → 單執行緒循序執行,未啟動新執行緒。run() 死迴圈無終止條件 → 程式無法正常結束。InterruptedException → 編譯錯誤或吞掉中斷訊號。