生产者 和 消费者 一个 小案例

来源:互联网 发布:产业安全数据直报 编辑:程序博客网 时间:2024/05/17 04:37

package com.thread;

 


/**
 * 生产者
 * @author CP
 *
 */
class prod implements Runnable{
 
 mount mou;
 
 public prod(mount mou) {
  this.mou = mou;
 }

 public void run() {
  bread brea=null;
  for (int i = 0; i < 20; i++) {
   brea=new bread(i);
   mou.pul(brea);
   
  }
 }
}


/**
 * 消费者
 * @author CP
 *
 */
class clinet implements Runnable{
 
 mount mou;
 
 public clinet(mount mou) {
  this.mou = mou;
 }

 public void run() {
  bread brea=null;
  for (int i = 0; i < 20; i++) {
   brea=mou.pop();
   
  }
 }
 
}


/**
 * 面包
 * @author CP
 *
 */
class bread{
 int id;
 public bread(int id) {
  this.id = id;
 }

 public String toString() {
  return "bread:"+id;
 }
}

/**
 * 容器
 * @author CP
 *
 */
class mount{
 
 int index=0;
 bread[] breadStrck=new bread[6];
 

 /**
  * 加入
  * @param brea
  */
 public synchronized  void pul(bread brea)
 {
  
   while(index==breadStrck.length)
   {
    try {
     this.wait();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
   System.out.println("-----生产--------"+brea+"-------------");
   breadStrck[index]=brea;
   index++;
   this.notifyAll();
 }
 
 
 /**
  * 取出
  * @return
  */
 public synchronized bread pop()
 {
  
   while(index==0)
   {
    try {
     this.wait();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
   
   index--;
   this.notifyAll();
   System.out.println("------消费-------"+breadStrck[index]+"-------------");
   return breadStrck[index];
  
 }
 
}

 

public class TestThread {

 public static void main(String[] args) {
  mount moun=new mount();
  clinet cli=new clinet(moun);
  prod pro=new prod(moun);
  
  Thread thrPro=new Thread(pro);
  Thread thrCli=new Thread(cli);
  
  thrPro.start();
  thrCli.start();
  
 }

}

原创粉丝点击