多執行緒環境下,若干執行緒循環等待彼此持有的資源,導致永久阻塞。
**破壞任一條件即可避免死鎖**。
模擬銀行借貸:系統資源有限,每個進程宣告最大需求,僅在安全序列存在時分配。
public class BankerAlgorithm {
static final int M = 5, N = 3; // 5 進程、3 資源類別
static int[][] MAX = {{7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3}};
static int[] AVAILABLE = {10,5,7};
static int[][] ALLOCATION = new int[M][N];
static int[][] NEED = new int[M][N];
public static boolean isSafe() {
int[] work = AVAILABLE.clone();
boolean[] finish = new boolean[M];
for (int k = 0; k < M; k++) {
boolean found = false;
for (int i = 0; i < M; i++) {
if (!finish[i] && canSatisfy(i, work)) {
for (int j = 0; j < N; j++) work[j] += ALLOCATION[i][j];
finish[i] = true; found = true; break;
}
}
if (!found) return false; // 無安全序列
}
return true;
}
private static boolean canSatisfy(int p, int[] work) {
for (int j = 0; j < N; j++) if (NEED[p][j] > work[j]) return false;
return true;
}
}
核心:**系統可用資源 ≥ 某進程剩餘需求** → 可推進 → 釋放資源 → 繼續下一進程。
public class DeadlockDemo {
static final Object LOCK_A = new Object(), LOCK_B = new Object();
public static void main(String[] args) {
new Thread(() -> { synchronized(LOCK_A) { sleep(100); synchronized(LOCK_B) { System.out.println("T1 done"); } } }).start();
new Thread(() -> { synchronized(LOCK_B) { sleep(100); synchronized(LOCK_A) { System.out.println("T2 done"); } } }).start();
}
static void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException ignored) {} }
}
執行緒 1 持有 A 等 B,執行緒 2 持有 B 等 A → **經典循環等待死鎖**。
| 策略 | 做法 | 適用場景 |
|---|---|---|
| 固定鎖順序 | 所有執行緒按相同順序獲取鎖 (hashCode 排序) | 多鎖並存的業務邏輯 |
| 嘗試鎖超時 | Lock.tryLock(timeout, TimeUnit) 失敗則釋放已得鎖重試 | 高併發、可重試業務 |
| 單一鎖/粗粒度鎖 | 用單一 ReentrantLock 保護整個資料結構 | 低爭用、簡單邏輯 |
| 無鎖資料結構 | ConcurrentHashMap、LongAdder、AtomicReference | 高讀低寫、計數器 |
| 避免在鎖內呼叫外部代碼 | 回呼/監聽器在鎖外執行 | 插件架構、事件總線 |
| 資源分級 | 將資源分層,只允許同層或由高到低請求 | 複雜系統資源管理 |
jstack -l pid:輸出執行緒堆疊,搜尋 BLOCKED 並檢查 waiting for 形成環。-XX:+PrintDeadlockDetection (JDK 11+) 定期輸出死鎖報告。synchronized,需要進階功能再升級 Lock。