public class ProCon{
public static void main(String[] args){
SyncStack stack = new SyncStack();
Consumer p = new Consumer(stack);
Producer c = new Producer(stack);
You y = new You(stack);
new Thread(c).start();
new Thread(y).start();
new Thread(p).start();
}
}
class Producer implements Runnable{
private SyncStack stack;
public Producer(SyncStack stack){
this.stack = stack;
}
public void run(){
for (int i = 0; i < stack.pro().length; i++){
stack.push("产品"+i);
}
}
}
class You implements Runnable{
SyncStack s;
public You(SyncStack s){
this.s = s;
}
public void run(){
for(int i = 0; i < s.pro().length; i++){
new SyncStack().yp();
}
}
}
class Consumer implements Runnable{
private SyncStack stack;
public Consumer(SyncStack stack) {
this.stack = stack;
}
public void run(){
for(int i = 0; i < stack.pro().length; i++){
System.out.println(stack.pop());
}
}
}
class SyncStack{
private String[] str = new String[10];
private int index;
public synchronized String pop(){
if(index == 0){
try{
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
//notify();
return "消费了-------------------"+str[--index];
}
public synchronized void push(String sst){
//notifyAll();
str[index] = sst;
index ++;
System.out.println("生产了:"+sst);
}
public synchronized void yp(){
// if(index == 0){
// try{
// wait();
// }catch (InterruptedException e){
// e.printStackTrace();
// }
// }
System.out.println("凑凑热闹的!!!!!!!!!!!"+"------"+index);
}
public String[] pro(){
return str;
}
}