多線程是 Java 並發編程基石。本文系統涵蓋線程建立、生命週期、常用方法、阻塞與控制、守護線程、優先級、讓步、同步機制、線程通訊與生產者消費者模式。
// 1. 繼承 Thread
class MyThread extends Thread {
@Override public void run() { /* 執行邏輯 */ }
}
new MyThread().start();
// 2. 實作 Runnable(推薦,支援 Lambda)
Runnable task = () -> { /* 執行邏輯 */ };
new Thread(task).start();
區別:Runnable 解耦任務與執行機制,方便提交至線程池;Thread 適合簡單繼承場景。
六大狀態:NEW → RUNNABLE → BLOCKED/WAITING/TIMED_WAITING → TERMINATED。
start():進入 RUNNABLE,等待 CPU 調度。sleep(ms):TIMED_WAITING,不釋放鎖。wait():WAITING,釋放鎖,需 notify() 喚醒。join():等待目標線程終止。yield():主動讓出 CPU,回 RUNNABLE。interrupt():中斷標記,配合 isInterrupted() 實現優雅停止。| 方法 | 說明 | 靜態/實例 |
|---|---|---|
sleep(long ms) | 當前線程休眠 | 靜態 |
yield() | 讓出 CPU | 靜態 |
join() | 等待該線程結束 | 實例 |
setDaemon(true) | 設為守護線程(需在 start 前) | 實例 |
setPriority(int) | 設優先級 1-10(MAX=10, NORM=5, MIN=1) | 實例 |
interrupt() | 發出中斷信號 | 實例 |
// 同步方法
public synchronized void add() { count++; }
// 同步區塊(推薦細粒度)
public void add() { synchronized(lock) { count++; } }
Lock lock = new ReentrantLock();
lock.lock(); try { /* critical section */ } finally { lock.unlock(); }
Lock 支援可中斷鎖、超時鎖、公平鎖、條件變數(Condition),功能更強大。
// Object 監視器
synchronized(obj) {
while (conditionNotMet) obj.wait();
// 執行任務
obj.notifyAll();
}
// Lock Condition(更靈活,支援多條件隊列)
Condition notFull = lock.newCondition();
Condition notEmpty = lock.newCondition();
lock.lock();
try {
while (queue.size() == capacity) notFull.await();
queue.add(item);
notEmpty.signal();
} finally { lock.unlock(); }
class Buffer {
private final Queue<Integer> queue = new LinkedList<>();
private final int capacity = 10;
private final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition(), notEmpty = lock.newCondition();
public void produce(int value) throws InterruptedException {
lock.lock();
try {
while (queue.size() == capacity) notFull.await();
queue.offer(value);
notEmpty.signal();
} finally { lock.unlock(); }
}
public int consume() throws InterruptedException {
lock.lock();
try {
while (queue.isEmpty()) notEmpty.await();
int val = queue.poll();
notFull.signal();
return val;
} finally { lock.unlock(); }
}
}
volatile boolean running 標誌 + interrupt() 打斷阻塞。掌握線程生命週期、同步工具(synchronized/Lock)、通訊機制(wait/notify/Condition)是並發編程核心。實務中優先使用高層抽象(ExecutorService、CompletableFuture、BlockingQueue、並發集合)降低複雜度與 Bug 風險。