/* 线程同步之生产者-消费者模型 该模型符合以下要求: 1、生产者只在仓储未满时生产,仓满则停止生产; 2、消费者只在仓储未空时消费,仓空则等待; 3、当消费者发现仓储为空时则通知生产者生产; 4、生产者在生产出可消费产品时则通知消费者来消费; */
1 package one; 2 class Go{ 3 public static final int MAX_NUM=100;//最大库存量 4 private int currennum;//当前库存 5 Go(){} 6 Go(int currennum){ 7 this.currennum=currennum; 8 } 9 public synchronized void produce(int neednum){ 10 System.out.println("要生产的产品数量"+neednum+"与现有仓储靓之和大于最大仓储量"+MAX_NUM+",所以不能生产!!"); 11 while(currennum+neednum>MAX_NUM){ 12 try { 13 this.wait();//使当前线程阻塞,并释放锁 14 } catch (InterruptedException e) { 15 // TODO Auto-generated catch block 16 e.printStackTrace(); 17 } 18 } 19 currennum+=neednum; 20 System.out.println("已经生产了"+neednum+",现在仓储量为:"+currennum); 21 this.notifyAll();//不释放锁,也不获得锁,仅通知其他线程可以竞争执行 22 } 23 public synchronized void consum(int neednum){ 24 while(currennum<neednum){ 25 System.out.println("现有仓储量不足,无法消费!!"); 26 try { 27 this.wait(); 28 } catch (InterruptedException e) { 29 // TODO Auto-generated catch block 30 e.printStackTrace(); 31 } 32 } 33 currennum-=neednum; 34 System.out.println("已经消费了"+neednum+",现在仓储量为:"+currennum); 35 this.notifyAll(); 36 } 37 } 38 class Producer extends Thread{ 39 private int neednum; 40 private Go go; 41 Producer(int neednum,Go go){ 42 this.neednum=neednum; 43 this.go=go; 44 } 45 public void run(){ 46 go.produce(neednum); 47 } 48 } 49 class Consumer extends Thread{ 50 private int neednum; 51 private Go go; 52 Consumer(int neednum,Go go){ 53 this.neednum=neednum; 54 this.go=go; 55 } 56 public void run(){ 57 go.consum(neednum); 58 } 59 } 60 public class Practice extends Thread{ 61 public static void main(String[] args){ 62 Go go=new Go(30); 63 new Consumer(50,go).start(); 64 new Consumer(20,go).start(); 65 new Consumer(30,go).start(); 66 new Producer(10,go).start(); 67 new Producer(10,go).start(); 68 new Producer(10,go).start(); 69 new Producer(10,go).start(); 70 new Producer(10,go).start(); 71 new Producer(80,go).start(); 72 } 73 }