java生產者消費者核心代碼

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;
   }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章