多線程在客戶端較簡單,服務端大量使用且問題更多。另一常見服務端問題是 死鎖:兩個或以上線程為使用某臨界資源無限等待。如兩人同時到達衛生間,互相禮讓「你先」,誰也不進——兩人即線程,衛生間即臨界資源,因謙讓導致無人使用。
死鎖不僅阻礙功能,還浪費資源,服務端危害大,開發中須注意避免。檢測困難且不必然重現,測試時需耐心觀察性能指標,若明顯下降極可能發生死鎖,再具體排查解決。根本原因是邏輯不夠嚴謹、考慮不周,通常需修改邏輯解決。
生活中常見「XXX優先」,多線程中每個線程可設置優先級。優先級高的線程排隊執行時獲更多 CPU 時間、響應更快。可根據邏輯需求,將需及時處理的線程設高優先級,對時間不敏感的設低優先級。
Thread 類定義三個優先級常量:
MAX_PRIORITY — 最高NORM_PRIORITY — 普通(默認)MIN_PRIORITY — 最低前文創建的線程未設置優先級,故為默認 NORM_PRIORITY。可用 setPriority(int) 方法設置:
public final void setPriority(int newPriority)
假設 t 為初始化線程,設為最高:
t.setPriority(Thread.MAX_PRIORITY);
若安全限制不允許設置,拋出 SecurityException。
package priority;
public class TestPriority {
public static void main(String[] args) {
PrintNumberThread p1 = new PrintNumberThread("高優先級");
PrintNumberThread p2 = new PrintNumberThread("普通優先級");
PrintNumberThread p3 = new PrintNumberThread("低優先級");
p1.setPriority(Thread.MAX_PRIORITY);
p2.setPriority(Thread.NORM_PRIORITY);
p3.setPriority(Thread.MIN_PRIORITY);
p1.start(); p2.start(); p3.start();
}
}
package priority;
public class PrintNumberThread extends Thread {
String name;
public PrintNumberThread(String name) { this.name = name; }
public void run() {
try {
for (int i = 0; i < 10; i++) {
System.out.println(name + ":" + i);
}
} catch (Exception e) {}
}
}
運行結果示例:
高優先級:0
高優先級:1
高優先級:2
普通優先級:0
高優先級:3
普通優先級:1
高優先級:4
普通優先級:2
高優先級:5
高優先級:6
高優先級:7
高優先級:8
高優先級:9
普通優先級:3
普通優先級:4
普通優先級:5
普通優先級:6
普通優先級:7
普通優先級:8
普通優先級:9
低優先級:0
低優先級:1
低優先級:2
低優先級:3
低優先級:4
低優先級:5
低優先級:6
低優先級:7
低優先級:8
低優先級:9
PrintNumberThread 循環輸出 0-9 無延遲。測試類創建三線程分別設高/普/低優先級並啟動。結果顯示高優先級獲更多執行時間優先完成,低優先級最後結束。線程調度由系統實現,高優先級優先執行,通過設置優先級可影響執行順序。
多線程基礎介紹至此:線程概念、三種實現方式、常見問題與解決。建立並發編程概念需大量練習。高級知識(如線程組)可在掌握基礎後深入學習。