單緩衝區 (`isEmpty` + `value`) 的 `wait/notify` 邏輯正確,但輸出過於規則 (生產-消費嚴格交替),**無法展示真實併發隨機性**,因無隨機延遲且單緩衝區強制同步。
class Buffer {
private int value;
private boolean empty = true;
public synchronized void put(int v) {
while (!empty) { try { wait(); } catch (InterruptedException e) {} }
value = v; empty = false; notifyAll();
}
public synchronized int get() {
while (empty) { try { wait(); } catch (InterruptedException e) {} }
empty = true; notifyAll(); return value;
}
}
class Producer extends Thread {
private Buffer buf; private Random rnd = new Random();
public Producer(Buffer b) { buf = b; }
public void run() {
for (int i=1; i<=5; i++) {
buf.put(i);
System.out.println("Put: " + i);
sleepRandom();
}
}
void sleepRandom() { try { Thread.sleep(rnd.nextInt(500)); } catch (InterruptedException e) {} }
}
class Consumer extends Thread {
private Buffer buf; private Random rnd = new Random();
public Consumer(Buffer b) { buf = b; }
public void run() {
for (int i=1; i<=5; i++) {
System.out.println("\t\tGet: " + buf.get());
sleepRandom();
}
}
void sleepRandom() { try { Thread.sleep(rnd.nextInt(500)); } catch (InterruptedException e) {} }
}
public class Main {
public static void main(String[] args) {
Buffer buf = new Buffer();
new Producer(buf).start();
new Consumer(buf).start();
}
}
class BoundedBuffer {
private final Queue q = new LinkedList<>();
private final int capacity;
public BoundedBuffer(int cap) { capacity = cap; }
public synchronized void put(int v) throws InterruptedException {
while (q.size() == capacity) wait();
q.offer(v); notifyAll();
}
public synchronized int get() throws InterruptedException {
while (q.isEmpty()) wait();
int v = q.poll(); notifyAll(); return v;
}
}
| 特性 | 單緩衝區 | 有界隊列緩衝區 |
|---|---|---|
| 併發度 | 嚴格交替 (鎖步) | 生產/消費可各自批次運行 |
| 適用場景 | 教學示範、極簡同步 | 實際系統、高吞吐、解耦 |
| 觀察隨機性 | 需額外 sleep | 天然呈現 |
建議:教學理解單槽 wait/notify 即可;實務專案直接用 `BlockingQueue` (如 `ArrayBlockingQueue`),JDK 內建、無鎖優化、支援超時、流式 API。