public class MyStack {
public static void main(String[] args) {
MyStack ms = new MyStack();
Thread producer = ms.new ProducerThread(ms);
Thread consumer = ms.new ConsumerThread(ms);
producer.start();
consumer.start();
producer = ms.new ProducerThread(ms);
producer.start();
}
private char[] cs = new char[6];
private int index = 0;
class ProducerThread extends Thread {
private MyStack s;
public ProducerThread(MyStack s) {
this.s = s;
}
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
s.push(c);
try {
sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
s.print();
}
}
}
class ConsumerThread extends Thread {
private MyStack s;
public ConsumerThread(MyStack s) {
this.s = s;
}
public void run() {
for (int i = 0; i < 52; i++) {
s.pop();
try {
sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
s.print();
}
}
}
private synchronized void push(char c) {
while (index == 6) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
cs[index] = c;
System.out.println(cs[index++] + " push");
}
private synchronized void pop() {
while (index == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(cs[--index] + " pop");
notify();
cs[index] = '\0';
}
private void print() {
for (int i = 0; i < index; i++) {
System.out.print(cs[i] + "\t");
}
System.out.println();
}
}