實驗代碼
public class PriorityDemo {
static volatile boolean stop = false;
static int countA = 0, countB = 0;
public static void main(String[] args) throws InterruptedException {
Thread tA = new Thread(() -> { while (!stop) countA++; }, "Thread-A");
Thread tB = new Thread(() -> { while (!stop) countB++; }, "Thread-B");
tA.setPriority(Thread.MIN_PRIORITY); // 1
tB.setPriority(Thread.MAX_PRIORITY); // 10
tA.start(); tB.start();
Thread.sleep(1000);
stop = true;
tA.join(); tB.join();
System.out.println("A (優先級1): " + countA);
System.out.println("B (優先級10): " + countB);
}
}
典型輸出結果
A (優先級1): 45,000,000
B (優先級10): 120,000,000

核心結論
- 高優先級線程獲得更多 CPU 時間片:計數器差異明顯證明調度器傾向分配更多資源給高優先級。
- 不保證執行順序或獨佔 CPU:低優先級線程仍在運行(countA > 0),只是頻率較低。
- 優先級只是「建議」而非強制:具體調度取決於 JVM 實現、作業系統調度策略(Windows 時間片輪轉、Linux CFS 等)。
優先級常量與範圍
Thread.MIN_PRIORITY = 1
Thread.NORM_PRIORITY = 5(預設)
Thread.MAX_PRIORITY = 10
最佳實踐建議
- **不要依賴優先級實現業務邏輯正確性**(如互斥、順序控制),請使用
synchronized、Lock、CountDownLatch 等同步工具。
- 優先級適合「輔助性」調優:如後台日誌刷盤線程設低優先級,即時計算線程設高優先級。
- 避免大量線程設為極端優先級,可能導致飢餓或系統響應下降。