Java 提供 10 個優先級常數(MIN_PRIORITY=1 到 MAX_PRIORITY=10,預設 NORM_PRIORITY=5)。優先級僅是對執行緒排程器的「建議」,具體執行順序取決於作業系統排程器,不保證高優先級必定先執行或獲得更多 CPU 時間。
import java.util.*;
public class upPRIThread {
public static void main(String[] args) throws Exception {
Thread1 t1 = new Thread1();
t1.start();
Thread2 t2 = new Thread2();
t2.start();
t1.setPriority(Thread.MIN_PRIORITY); // 1
t2.setPriority(Thread.MIN_PRIORITY); // 1
new Thread().sleep(105); // 讓兩條都以低優先級運行一段
t2.setPriority(Thread.MAX_PRIORITY); // 10:提升 t2 優先級
new Thread().sleep(10500); // 觀察長時間行為
}
// 執行緒 1:始終低優先級
static class Thread1 extends Thread {
public void run() {
while (true) {
try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); }
System.out.println("我是執行緒111");
}
}
}
// 執行緒 2:中途提升優先級
static class Thread2 extends Thread {
public void run() {
while (true) {
try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); }
System.out.println("我是執行緒222.........................");
}
}
}
}
| 方法/常數 | 說明 |
|---|---|
setPriority(int) | 設定優先級(1-10),超出範圍拋出 IllegalArgumentException |
getPriority() | 取得目前優先級 |
MIN_PRIORITY (1) | 最低優先級 |
NORM_PRIORITY (5) | 預設優先級 |
MAX_PRIORITY (10) | 最高優先級 |
| 誤區 | 事實 | 建議 |
|---|---|---|
| 高優先級保證先執行 | 僅是建議,OS 可能忽略 | 不依賴優先級實現業務邏輯順序 |
| 優先級解決飢餓問題 | 可能加劇低優先級飢餓 | 使用公平鎖、信號量等同步機制 |
| 即時系統必須用高優先級 | Java 非即時語言,GC 停頓不可控 | 即時需求用 RTSJ 或原生代碼 |
相關概念:setDaemon(true) 設定守護執行緒,JVM 僅剩守護執行緒時會自動退出。優先級與守護屬性獨立。
ThreadPoolExecutor 透過隊列與核心數控制並發,而非優先級Thread.ofVirtual(),大量輕量執行緒無需手動調優先級優先級是精細調整工具,非架構級解決方案。優先掌握執行緒池、非同步編程等現代並發模式。