java生產者消費者實例代碼

public class ProCon{ //主方法

public static void main(String[] args){
SyncStack stack = new SyncStack();
Consumer p = new Consumer(stack);
Producer c = new Producer(stack);


new Thread(p).start();
new Thread(c).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++){
    String product = "產品"+i;
    stack.push(product);
    System.out.println("生產了: "+product);
    try{
     Thread.sleep(200);
     }catch(InterruptedException e)
      {
       e.printStackTrace();
     }
   }
}
}

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++){
    String product = stack.pop();
    System.out.println("消費了: "+product);
    try{
     Thread.sleep(1000);
   }catch(InterruptedException e){
     e.printStackTrace();
     }
    }
   }
}

class SyncStack{   // 此類是(本質上:共同訪問的)共享數據區域
private String[] str = new String[10];
    private int index;
   
    public synchronized void push(String sst){ //供生產者調用
    if(index == sst.length()){
     try{
      wait();
     }catch(InterruptedException e){
       e.printStackTrace();
      }
    }
   this.notify(); //喚醒在此對象監視器上等待的單個線程
   str[index] = sst;
   index++;
}

   public synchronized String pop(){   //供消費者調用
    if(index == 0){
     try{
      wait();
      }catch (InterruptedException e){
       e.printStackTrace();
      }
   }
    notify();
    index--;
    String product = str[index];
    return product;
   }

    public String[] pro(){ //就是定義一個返回值爲數組的方法,返回的是一個String[]引用
     return str;   //這是一個String[]引用
   }
}

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