兩個或多個線程互相持有對方需要的鎖,並等待對方釋放,導致無限阻塞。如兩人禮讓進廁所,誰也不先進。
public class DeadlockDemo {
private static final Object LOCK_A = new Object();
private static final Object LOCK_B = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
synchronized (LOCK_A) {
sleep(100);
synchronized (LOCK_B) { System.out.println("T1 獲得雙鎖"); }
}
}, "Thread-1");
Thread t2 = new Thread(() -> {
synchronized (LOCK_B) {
sleep(100);
synchronized (LOCK_A) { System.out.println("T2 獲得雙鎖"); }
}
}, "Thread-2");
t1.start(); t2.start();
}
static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException ignored) {} }
}
輸出卡住,無任何後續日誌 —— 死鎖發生。
Found one Java-level deadlock 及鎖鏈。thread -b 一鍵定位阻塞線程與鎖持有者。ReentrantLock.tryLock(timeout) 避免無限等待。Thread.MIN_PRIORITY = 1Thread.NORM_PRIORITY = 5(默認)Thread.MAX_PRIORITY = 10Thread t = new Thread(task);
t.setPriority(Thread.MAX_PRIORITY); // 必須在 start() 前設置
t.start();
public class PriorityDemo {
static class Printer extends Thread {
public Printer(String name) { super(name); }
@Override public void run() {
for (int i = 0; i < 5; i++) System.out.println(getName() + ": " + i);
}
}
public static void main(String[] args) {
Thread high = new Printer("高優先級");
Thread norm = new Printer("普通優先級");
Thread low = new Printer("低優先級");
high.setPriority(Thread.MAX_PRIORITY);
norm.setPriority(Thread.NORM_PRIORITY);
low.setPriority(Thread.MIN_PRIORITY);
high.start(); norm.start(); low.start();
}
}
輸出中高優先級線程獲得更多 CPU 時間片,但不保證執行順序,受 OS 調度器影響大。
| 誤區 | 事實 |
|---|---|
| 高優先級線程一定先跑完 | 優先級只影響調度概率,非決定性;I/O、鎖、睡眠會打斷 |
| 用優先級解決業務邏輯順序 | 錯誤!業務順序靠同步機制(CountDownLatch、Future、信號量)保證 |
| 大量設置高優先級提升性能 | 會導致餓死、系統線程(GC、JIT)被擠佔,反而降低整體吞吐 |
| 跨平台行為一致 | Windows/Linux/Solaris 對優先級映射不同,表現差異大 |
NORM_PRIORITY,極少手動調整。MIN_PRIORITY。PriorityBlockingQueue)控制任務執行順序,而非線程優先級。死鎖是設計缺陷,通過固定鎖序、縮小同步範圍、超時機制從根源消除;線程優先級是調度提示而非控制指令,濫用反而有害。多線程核心能力在於正確同步、無鎖編程、線程池隔離、可觀測性建設,而非花哨的優先級技巧。