替代方案:使用 interrupt() + 旗標檢查 + Thread.interrupted() 協作式停止。
執行緒 A 持有鎖 1 等待鎖 2,執行緒 B 持有鎖 2 等待鎖 1,雙方永久阻塞。
// 錯誤:順序不一致
// Thread A: lock(A) → lock(B)
// Thread B: lock(B) → lock(A)
// 正確:全域固定順序
private static final Object LOCK1 = new Object();
private static final Object LOCK2 = new Object();
void methodA() {
synchronized (LOCK1) {
synchronized (LOCK2) { /* ... */ }
}
}
void methodB() {
synchronized (LOCK1) { // 相同順序
synchronized (LOCK2) { /* ... */ }
}
}
tryLock(timeout):超時放棄,避免永久等待。執行緒持續嘗試操作但永遠失敗(如兩人走廊相讓),CPU 100% 但無進展。
Thread.sleep(random.nextInt(100))。synchronized、volatile、Atomic* 修正。ExecutorService 限制並發數。Semaphore 控制許可數。public class ThreadProbe extends Thread {
@Override
public void run() {
while (true) {
Thread[] threads = new Thread[1000];
int count = Thread.enumerate(threads);
for (int i = 0; i < count; i++) {
Thread t = threads[i];
System.out.printf("%s\t%d\t%b\t%b%n",
t.getName(), t.getPriority(), t.isAlive(), t.isDaemon());
}
try { Thread.sleep(5000); } catch (InterruptedException ignored) {}
}
}
}
jstack :列印所有執行緒堆疊(含鎖資訊,死鎖偵測)。jconsole/VisualVM:圖形化監控執行緒狀態、記憶體、CPU。ThreadMXBean:程式化取得執行緒資訊、偵測死鎖。thread.setName("OrderProcessor-1")。ThreadLocal 隔離執行緒專屬資料。ConcurrencyTestRunner、jcstress)。-XX:+PrintConcurrentLocks 協助 jstack 分析。