1 //资源类 1.资源变量 2.生产方法 3.消费方法 2 class Box{ 3 private int product=0; //资源变量 4 5 public synchronized void addProduct(){ 6 7 //首先要判断盒子中产品是否大于10,大于就停止生产,否则就继续生产 8 if(this.product >10){ 9 try{ 10 this.wait(); 11 }catch(InterruptedException e){ 12 e.printStackTrace(); 13 } 14 15 }else{ 16 17 //打印生产了多少个产品 18 System.out.println("这是生产的第" + this.product + "个产品"); 19 this.product++; 20 21 //需要唤醒消费者线程开始消费 22 this.notifyAll(); 23 } 24 25 } 26 27 public synchronized void getProduct(){ 28 29 //首先要判断盒子中产品是否小0,小于就停止消费,否则就继续消费 30 if(this.product <= 0){ 31 try{ 32 this.wait(); 33 }catch(InterruptedException e){ 34 e.printStackTrace(); 35 } 36 37 }else{ 38 39 //打印消费了多少个产品 40 System.out.println("这是消费的第" + this.product + "个产品"); 41 this.product--; 42 43 //需要唤醒生产者线程开始消费 44 this.notifyAll(); 45 } 46 47 } 48 49 } 50 51 //生产者调用addProducter方法 52 class Producter implements Runnable 53 { 54 //资源对象的引用 55 Box box; 56 public Producter(Box box){ 57 this.box = box; 58 } 59 60 public void run(){ 61 System.out.println("生产者开始生产了"); 62 while(true){ 63 try{ 64 Thread.sleep((int) Math.random()*10000); 65 } 66 catch(InterruptedException e) 67 { 68 e.printStackTrace(); 69 } 70 71 box.addProduct(); 72 } 73 74 } 75 76 } 77 78 //消费者调用getProduct方法 79 class Consumer implements Runnable 80 { 81 //资源对象的引用 82 Box box; 83 public Consumer(Box box){ 84 this.box = box; 85 } 86 87 public void run(){ 88 System.out.println("消费者开始消费了"); 89 while(true){ 90 try{ 91 Thread.sleep((int) Math.random()*10000); 92 } 93 catch(InterruptedException e) 94 { 95 e.printStackTrace(); 96 } 97 98 box.getProduct(); 99 } 100 101 } 102 } 103 104 public class ThreadDemo{ 105 106 //程序测试入口 107 public static void main(String[] args){ 108 109 Box box = new Box(); 110 111 Producter pd = new Producter(box); 112 Consumer cn = new Consumer(box); 113 114 new Thread(pd).start(); 115 new Thread(cn).start(); 116 117 } 118 }