兩個線程,一個負責印 1–100 的奇數,一個負責印偶數。規則是:線程 1 印 5 個之後換線程 2,線程 2 印 5 個之後再換回線程 1,如此循環。
關鍵在於用同一個物件作為鎖,再用一個 state 變數表示「現在輪到誰」。沒輪到的線程就 wait(),輪到的印完 5 個後改寫 state 並 notifyAll()。
public class Test {
// state==1 表示線程1開始列印,state==2 表示線程2開始列印
private static int state = 1;
private static int num1 = 1;
private static int num2 = 2;
public static void main(String[] args) {
final Test t = new Test();
new Thread(new Runnable() {
@Override
public void run() {
while (num1 < 100) {
// 兩個線程都以 t 作為鎖,確保每個交替期間只有一個線程在列印
synchronized (t) {
// 若 state!=1,表示尚未輪到線程1,於是 t.wait() 等待被喚醒
if (state != 1) {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// state=1 時,線程1連續印 5 個奇數
for (int j = 0; j < 5; j++) {
System.out.println(num1);
num1 += 2;
}
// 交接棒給線程2
state = 2;
// notifyAll() 喚醒在 t 上等待的線程2,同時線程1離開同步區塊釋放鎖
t.notifyAll();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (num2 < 100) {
synchronized (t) {
if (state != 2) {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 0; j < 5; j++) {
System.out.println(num2);
num2 += 2;
}
state = 1;
t.notifyAll();
}
}
}
}).start();
}
}
wait() 一定要包在 synchronized 區塊裡,否則會丟出 IllegalMonitorStateException;喚醒時機也要注意,若列印完畢的線程不再呼叫 notifyAll(),另一個線程可能永久卡在 wait()。若把 if 改成 while 來檢查 state,還能多擋一層「虛假喚醒」的風險,是更保險的寫法。