class Shared {
static final int MAX_BUFFER_SIZE = 3;
static Queue<String> buffer = new ArrayDeque<>();
private static final Object lock = new Object();
static void waitUntilNotified() {
try {
synchronized (lock) {
lock.wait();
}
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
static void notifyWaitingThread() {
synchronized (lock) {
lock.notify();
}
}
}
// {
class Consumer implements Runnable {
public void run() {
while (true) {
if (Shared.buffer.size() == 0) {
Shared.waitUntilNotified();
}
consume();
if (shouldNotifyProducers()) {
Shared.notifyWaitingThread();
}
}
}
private void consume() {
System.out.println("Consumed: " + Shared.buffer.remove());
}
private boolean shouldNotifyProducers() {
return Shared.buffer.size() == Shared.MAX_BUFFER_SIZE - 1;
}
}
class Producer implements Runnable {
private static int i = 0;
public void run() {