| 維度 | 進程 | 線程 |
|---|---|---|
| 定義 | 執行中程式的實例,資源分配單位 | 進程內的執行路徑,調度執行單位 |
| 記憶體 | 獨立地址空間 | 共享進程堆/方法區,私有棧/PC寄存器 |
| 開銷 | 創建/切換昂貴 | 輕量級,上下文切換快 |
| 通信 | IPC (管道/套接字/共享內存) | 共享內存直接讀寫,需同步 |
| 方式 | 核心類/介面 | 優點 | 缺點 | 推薦場景 |
|---|---|---|---|---|
| 1. 繼承 Thread | class MyThread extends Thread | 簡單直觀,this 即線程對象 | 單繼承限制,邏輯與控制耦合 | 簡單測試、教學演示 |
| 2. 實現 Runnable | class Task implements Runnable | 分離任務與執行,支援共享實例、線程池 | 需包裝 new Thread(task) | 最通用推薦 |
| 3. 匿名內部類 | new Thread() { run() {...} } | 就地定義,適合一次性邏輯 | 可讀性差,難複用 | 簡單一次性任務 |
| 4. 實現 Callable + FutureTask | Callable<V>, FutureTask<V> | 有返回值、可拋異常、配合線程池 | 稍繁瑣 | 需結果/異常的異步計算 |
class CounterTask implements Runnable {
private int count = 100;
@Override public void run() {
while (true) {
synchronized (this) { // 共享實例 this 為鎖
if (count <= 0) break;
try { Thread.sleep(100); } catch (InterruptedException ignored) {}
System.out.println(Thread.currentThread().getName() + " 剩餘: " + count--);
}
}
}
}
public class Demo {
public static void main(String[] args) {
CounterTask task = new CounterTask(); // 單一實例
new Thread(task, "線程-A").start();
new Thread(task, "線程-B").start();
new Thread(task, "線程-C").start();
}
}
關鍵:synchronized(this) 確保三線程互斥訪問共享 count,輸出 100→0 無重複無遺漏。
| 同步形式 | 鎖對象 | 範圍 |
|---|---|---|
非靜態方法 synchronized void m() | this | 同一實例所有非靜態同步方法互斥 |
靜態方法 synchronized static void m() | ClassName.class | 全類所有靜態同步方法互斥 |
同步塊 synchronized(obj) | obj (任意對象) | 自定義粒度,需確保共享同一鎖實例 |
lock.wait()、lock.notify()notifyAll 喚醒全部class SharedBuffer {
private final List buffer = new ArrayList<>();
private final int capacity = 10;
public synchronized void produce(int value) throws InterruptedException {
while (buffer.size() == capacity) wait(); // 滿等待
buffer.add(value);
notifyAll(); // 喚醒消費者
}
public synchronized int consume() throws InterruptedException {
while (buffer.isEmpty()) wait(); // 空等待
int value = buffer.remove(0);
notifyAll(); // 喚醒生產者
return value;
}
}
鎖屬於任意對象,一個程式可有多把鎖。線程需在持有特定鎖的同步塊內調用該鎖的 wait/notify,故定義在 Object 通用。
NEW → (start) → RUNNABLE ↔ (時間片/鎖/IO) → BLOCKED/WAITING/TIMED_WAITING → (結束) → TERMINATED

已棄用:stop() (破壞鎖一致性)、suspend()/resume() (易死鎖)
class Worker implements Runnable {
private volatile boolean running = true;
public void run() {
while (running && !Thread.currentThread().isInterrupted()) {
try {
// 業務邏輯
TimeUnit.MILLISECONDS.sleep(200); // 可中斷阻塞
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 重設標誌
break;
}
}
// 清理資源
}
public void shutdown() { running = false; }
}
| 方法 | 類型 | 行為 | 中斷標誌 |
|---|---|---|---|
interrupt() | 實例 | 設置標誌;阻塞處拋 InterruptedException 並清除標誌 | 設置/清除後可重設 |
isInterrupted() | 實例 | 只讀檢查,不清除 | 只讀 |
interrupted() | static | 檢查當前線程並清除標誌 | 讀取並清除 |
public class Singleton {
private static volatile Singleton instance; // volatile 禁止指令重排
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) { // 第一次檢查:無鎖快速路徑
synchronized (Singleton.class) { // 類級鎖
if (instance == null) { // 第二次檢查:防重複創建
instance = new Singleton();
}
}
}
return instance;
}
}
lock.lockInterruptibly()lock.tryLock()、tryLock(timeout)new ReentrantLock(true)lock.newCondition() 精確喚醒class BoundedBuffer {
private final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
private final Object[] items = new Object[10];
private int putPtr, takePtr, count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length) notFull.await(); // 精確等待
items[putPtr] = x;
if (++putPtr == items.length) putPtr = 0;
++count;
notEmpty.signal(); // 只喚醒消費者
} finally { lock.unlock(); }
}
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0) notEmpty.await();
Object x = items[takePtr];
if (++takePtr == items.length) takePtr = 0;
--count;
notFull.signal(); // 只喚醒生產者
return x;
} finally { lock.unlock(); }
}
}
對比優勢:notifyAll 驚群效應 vs signal 精確喚醒;多條件變量語義清晰;支援 awaitUninterruptibly、awaitUntil 等進階等待。
| 類 | 用途 | 核心方法 |
|---|---|---|
| CountDownLatch | 一組線程等待計數歸零 | countDown(), await() |
| CyclicBarrier | 一組線程相互等待屏障點 | await(), barrierAction |
| Semaphore | 信號量控制並發訪問數 | acquire(), release() |
| Exchanger | 雙線程交換數據 | exchange(V) |
| Phaser | 多階段屏障 (JDK 7+) | arriveAndAwaitAdvance() |