1 package cn.ftf.threadcooperation; 2 /** 3 * 协作模型:生产者消费者模式实现方式一:管程法,借助一个缓冲区 4 * @author 房廷飞 5 * 6 */ 7 8 public class CoTest01 { 9 public static void main(String[] args) { 10 SyContainer sy=new SyContainer(); 11 Productor pro=new Productor(sy); 12 pro.start(); 13 Consumer con = new Consumer(sy); 14 con.start(); 15 } 16 } 17 18 19 //生产者 20 class Productor extends Thread{ 21 SyContainer sycon; 22 public Productor(SyContainer sycon) { 23 super(); 24 this.sycon = sycon; 25 } 26 public void run() { 27 for(int i=0;i<100;i++) { 28 System.out.println("生产第"+i+"个馒头"); 29 sycon.push(new Streamedbun(i)); 30 } 31 } 32 } 33 34 35 //消费者 36 class Consumer extends Thread{ 37 SyContainer sycon; 38 39 public Consumer(SyContainer sycon) { 40 super(); 41 this.sycon = sycon; 42 } 43 public void run() { 44 for(int i=0;i<100;i++) { 45 System.out.println("消费第"+sycon.pop().id+"个馒头"); 46 47 } 48 } 49 } 50 51 52 53 //缓冲区 54 class SyContainer{ 55 Streamedbun[] buns=new Streamedbun[100]; 56 int count = 0; //计数器 57 //存 58 public synchronized void push(Streamedbun bun){ //加入synchronized关键字 59 //加入可以生产条件:需要容器存在空间;不能生产,抛锁等待,避免容器越界错误 60 if(count==buns.length) { 61 try { 62 this.wait(); 63 } catch (InterruptedException e) { 64 // TODO Auto-generated catch block 65 e.printStackTrace(); 66 } 67 } 68 buns[count] = bun; 69 count++; 70 this.notify(); //唤醒所有的等待者 71 } 72 //取 73 public synchronized Streamedbun pop(){ ////加入synchronized关键字 74 //加入可以取的条件,避免容器越界错误 75 if(count==0) { 76 try { 77 this.wait(); //每个对象都有一个wait,将锁抛出,线程阻塞,生产者通知消费解除 78 } catch (InterruptedException e) { 79 // TODO Auto-generated catch block 80 e.printStackTrace(); 81 } 82 } 83 count--; 84 Streamedbun bun=buns[count]; 85 this.notify(); //唤醒所有的等待者 86 return bun; 87 } 88 } 89 90 91 92 //数据(馒头) 93 class Streamedbun{ 94 int id; 95 public Streamedbun(int id) { 96 super(); 97 this.id = id; 98 } 99 }