public class Test {
private Object mutex = new Object();
private volatile boolean isEmpty = true;
private volatile boolean isFull = false;
private String buffer = null;
public static void main(String[] args) {
new Test().start();
}
public void start() {
Thread consumer = new Thread(new Consumer(mutex));
Thread producer = new Thread(new Producer(mutex));
consumer.start();
producer.start();
}
class Producer implements Runnable {
private Object mutex = null;
public Producer(Object mutex) {
this.mutex = mutex;
}
@Override
public void run() {
int count = 0;
while (true) {
while (isFull) {
try {
synchronized (mutex) {
mutex.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer = "" + ++count;
System.out.println(Thread.currentThread().getName() + " produce " + buffer);
isFull = true;
isEmpty = false;
synchronized (mutex) {
mutex.notifyAll();
}
}
}
}
class Consumer implements Runnable {
private Object mutex = null;
public Consumer(Object mutex) {
this.mutex = mutex;
}
@Override
public void run() {
while (true) {
while (isEmpty) {
try {
synchronized (mutex) {
mutex.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " consume " + buffer);
buffer = null;
isEmpty = true;
isFull = false;
synchronized (mutex) {
mutex.notifyAll();
}
}
}
}
}