//
class MyStack{
int[] max = null;
int index = 0;
public MyStack(int m){
max = new int[m];
}
public synchronized void push(int param){
// while, ,
while(index>=max.length){
try {
System.out.println(" WAIT===========================");
this.wait();
System.out.println(" notify");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
max[index] = param;
index ++ ;
}
public synchronized int pop(){
// while, ,
while(index<=0){
try {
System.out.println(" WAIT===========================");
this.wait();
System.out.println(" notify");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
index --;
return max[index];
}
}
//
class Producer implements Runnable{
MyStack myStack = null;
int count;
public Producer(MyStack ms,int count){
myStack = ms;
this.count = count;
}
public void run(){
for(int i=1;i<=myStack.max.length;i++){
myStack.push(i);
System.out.println(" "+count+" , "+i+" :"+i);
try {
Thread.sleep((int)(Math.random()*300));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//
class Consumer implements Runnable{
MyStack myStack = null;
int count;
int i;
public Consumer(MyStack ms,int count){
myStack = ms;
this.count = count;
}
public void run(){
for(int i=1;i<=myStack.max.length;i++){
int x = myStack.pop();
System.out.println(" "+count+" , "+i+" :"+x);
try {
Thread.sleep((int)(Math.random()*300));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//
public class ProducerConsumerTest {
public static void main(String[] args) {
MyStack ms = new MyStack(10);
Thread p1 = new Thread(new Producer(ms,1));
Thread p2 = new Thread(new Producer(ms,2));
Thread p3 = new Thread(new Producer(ms,3));
Thread c1 = new Thread(new Consumer(ms,1));
Thread c2 = new Thread(new Consumer(ms,2));
p1.start();
p2.start();
p3.start();
c1.start();
c2.start();
}
}