一、代码:
1 package zz.produceandconsumer; 2 3 import java.util.LinkedList; 4 5 public class Storage { 6 7 private final static int MAX_NUM=100; 8 9 private volatile LinkedList<Object> list=new LinkedList<Object>(); 10 11 public void produce(int pNum){ 12 synchronized(list){ 13 if(list.size()+pNum>MAX_NUM){ 14 System.out.println("当前商品数量:"+list.size()+",欲生产数量:"+pNum+",超过最大容量:"+MAX_NUM+"."); 15 try { 16 list.wait(); 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 } 21 // while(list.size()+pNum>MAX_NUM){ 22 // System.out.println("当前商品数量:"+list.size()+",欲生产数量:"+pNum+",超过最大容量"+MAX_NUM+"."); 23 // try { 24 // list.wait(); 25 // } catch (InterruptedException e) { 26 // e.printStackTrace(); 27 // } 28 // } 29 int i=0; 30 while(i<pNum){ 31 System.out.println("欲生产:"+pNum+",list.size:"+list.size()+",最大值:"+MAX_NUM+",i:"+i); 32 list.add(new Object()); 33 i++; 34 } 35 System.out.println("生产了"+pNum+"个商品,仓库中存货"+list.size()+"."); 36 list.notifyAll(); 37 } 38 } 39 40 public void consumer(int cNum){ 41 synchronized(list){ 42 // if(cNum>list.size()){ 43 // System.out.println("当前商品数量:"+list.size()+",欲消费数量:"+cNum+",数量不足."); 44 // try { 45 // list.wait(); 46 // } catch (InterruptedException e) { 47 // e.printStackTrace(); 48 // } 49 // } 50 while(cNum>list.size()){ 51 System.out.println("当前商品数量:"+list.size()+",欲消费数量:"+cNum+",数量不足."); 52 try { 53 list.wait(); 54 } catch (InterruptedException e) { 55 e.printStackTrace(); 56 } 57 } 58 int i=0; 59 if(cNum>list.size()){ 60 System.out.println("error"); 61 } 62 while(i<cNum){ 63 // System.out.println("size:"+list.size()+",i:"+i+",cNum:"+cNum); 64 list.remove(); 65 i++; 66 } 67 System.out.println("消费了"+cNum+"个商品,仓库中存货"+list.size()+"."); 68 list.notifyAll(); 69 } 70 } 71 72 }