java生产者消费者实例代码

来源:互联网 发布:淘宝如何刷好评赚钱 编辑:程序博客网 时间:2024/06/05 12:07

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[]引用
   }
}