使用 setPriority(int) 設置,範圍 1-10,預設 5。高優先級線程獲得更多 CPU 時間片,但不保證執行順序。
t1.setPriority(Thread.NORM_PRIORITY + 3); // 優先級 8
t2.setPriority(Thread.NORM_PRIORITY); // 優先級 5
通過 synchronized 鎖定共享資源,防止併發訪問導致數據不一致。
class Timer {
private static int num = 0;
public synchronized void add(String name) { // 或 synchronized(this)
num++;
System.out.println(name + ":第 " + num + " 個使用");
}
}
兩線程互相持有對方需要的鎖,導致永久等待。
// 線程 1
synchronized(o1) { sleep(500); synchronized(o2) { System.out.println("1"); } }
// 線程 2
synchronized(o2) { sleep(500); synchronized(o1) { System.out.println("0"); } }
避免策略:固定鎖獲取順序、使用 tryLock 超時機制、減少鎖範圍。
使用 wait()/notify() 實現緩衝區協調。
class SyncStack {
private int index = 0;
private char[] data = new char[6];
public synchronized void push(char c) {
if (index == data.length) { wait(); }
data[index++] = c;
notify();
}
public synchronized char pop() {
if (index == 0) { wait(); }
notify();
return data[--index];
}
}
sleep() 不釋放鎖;wait() 釋放鎖並進入等待隊列。join() 合併線程,等待目標線程結束。yield() 讓出 CPU,重新參與調度。掌握線程優先級控制、同步機制、死鎖預防與經典協作模式,是編寫健壯多線程程序的核心技能。