多線程讓程式擁有多條獨立執行路徑,邏輯上「同時」運行。Java 提供 java.lang.Thread 類封裝線程控制,核心在於如何指定線程執行代碼——兩種標準模式各有優勢。
public class MyThread extends Thread {
private final int id;
public MyThread(int id) { this.id = id; }
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread-" + id + ": count=" + i);
}
}
public static void main(String[] args) {
for (int i = 1; i <= 5; i++)
new MyThread(i).start(); // 必須調用 start(),而非 run()
}
}
this 訪問線程方法(getName(), sleep() 等)。Applet、HttpServlet 等框架基類,無法再繼承 Thread。public class MyTask implements Runnable {
private final int id;
public MyTask(int id) { this.id = id; }
@Override
public void run() {
for (int i = 1; i <= 5; i++)
System.out.println("Task-" + id + ": count=" + i);
}
public static void main(String[] args) {
for (int i = 1; i <= 5; i++)
new Thread(new MyTask(i)).start(); // 將 Runnable 傳給 Thread 構造器
}
}
Runnable 實例可提交給線程池、ExecutorService、CompletableFuture 等高級 API。run() 中需 Thread.currentThread() 獲取線程上下文,稍顯間接。| 維度 | extends Thread | implements Runnable |
|---|---|---|
| 繼承靈活性 | 佔用唯一繼承名額 | 無影響 |
| 任務復用 | 難(綁定線程實例) | 易(分離任務邏輯) |
| 線程池適配 | 不直接支援 | 原生支援 |
| 訪問線程方法 | 直接 this.xxx() | Thread.currentThread().xxx() |
NEW → RUNNABLE → (RUNNING) → BLOCKED/WAITING/TIMED_WAITING → TERMINATED
start():請求 JVM 配置線程,異步調用 run()。sleep()/join():靜態方法操作當前線程,不釋放鎖。wait()/notify():Object 實例方法,需在 synchronized 塊中調用,釋放鎖進入等待集。interrupt():設置中斷標誌,配合 InterruptedException 實現協作式取消。Runnable + 線程池 (Executors),手動 new Thread 僅用於簡單測試/原型。synchronized、ReentrantLock、volatile、Atomic*、Concurrent* 集合。thread.setName("Order-Processor-" + id),日誌排查效率倍增。Thread.setDefaultUncaughtExceptionHandler() 統一捕獲非預期崩潰。多線程是利用多核 CPU、實現高併發的基石。從 Runnable 開始,逐步掌握同步工具、線程池、非阻塞算法,構建健壯的並發系統。