程式碼展示經典 **單缓衝區** 生產者-消費者模型:
Res 共享資源:name, sex, flag (是否有資料)。set() 生產:flag==true → wait();寫入後 flag=true; notify()。out() 消費:flag==false → wait();讀取後 flag=false; notify()。public class Res {
private String name, sex;
private boolean flag = false; // false=空, true=滿
public synchronized void set(String name, String sex) {
while (flag) { // 用 while 防虛假喚醒
try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); }
}
this.name = name; this.sex = sex;
flag = true;
this.notify(); // 喚醒消費者
}
public synchronized void out() {
while (!flag) {
try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); }
}
System.out.println(name + "...." + sex);
flag = false;
this.notify(); // 喚醒生產者
}
}
Res r?Input(Res r) { this.r = r; } 將**同一個共享物件引用**傳給生產者與消費者執行緒,確保它們操作的是**同一把鎖、同一組旗標**。若各自 new Res() 則無法協同。
java.util.concurrent.ArrayBlockingQueue 替代手動 wait/notify,簡潔且無錯誤。notifyAll() 避免信號遺漏。理解「共享物件 + 同步鎖 + 旗標 + wait/notify」四要素,即可掌握 Java 線程協作核心。