生产者消费者案例
实现代码:
1 public class Box { 2 //定义一个成员变量,表示第x瓶奶 3 private int milk; 4 //定义一个成员变量,表示奶箱的状态 5 private boolean state=false; 6 7 //提供存储牛奶和获取牛奶的操作 8 public synchronized void put(int milk) { 9 //如果有牛奶,等待消费 10 if(state) { 11 try { 12 wait(); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } 16 } 17 18 //如果没有牛奶,就生产牛奶 19 this.milk=milk; 20 System.out.println("送奶工将第"+this.milk+"瓶奶放入奶箱"); 21 22 //生产完毕之后,修改奶箱状态 23 state=true; 24 25 //唤醒其他等待的线程 26 notifyAll(); 27 } 28 29 public synchronized void get() { 30 //如果没有牛奶,等待生产 31 if(!state) { 32 try { 33 wait(); 34 } catch (InterruptedException e) { 35 e.printStackTrace(); 36 } 37 } 38 39 //如果有牛奶,就消费牛奶 40 System.out.println("用户拿到第"+this.milk+"瓶奶"); 41 42 //消费完毕之后,修改奶箱状态 43 state=false; 44 45 //唤醒其他等待的线程 46 notifyAll(); 47 } 48 }public class Box {
1 public class Producer implements Runnable{ 2 private Box b; 3 4 public Producer(Box b) { 5 this.b=b; 6 } 7 8 @Override 9 public void run() { 10 for(int i=1;i<=6;i++) { 11 b.put(i); 12 } 13 } 14 15 }public class Producer implements Runnable{
1 public class Customer implements Runnable{ 2 private Box b; 3 4 public Customer(Box b) { 5 this.b=b; 6 } 7 8 @Override 9 public void run() { 10 while(true) { 11 b.get(); 12 } 13 } 14 15 }public class Customer implements Runnable{
1 public class BoxDemo { 2 3 public static void main(String[] args) { 4 //创建奶箱对象,这是共享数据区域 5 Box b=new Box(); 6 7 //创建生产者对象,把奶箱对象作为构造方法参数传递,因为在这个类中要调用存储牛奶的操作 8 Producer p=new Producer(b); 9 //创建消费者对象,把奶箱对象作为构造方法参数传递,因为在这个类中要调用获取牛奶的操作 10 Customer c=new Customer(b); 11 12 //创建2个线程对象,分别把生产者对象和消费者对象作为构造方法参数传递 13 Thread t1=new Thread(p); 14 Thread t2=new Thread(c); 15 16 //启动线程 17 t1.start(); 18 t2.start(); 19 } 20 }public class BoxDemo {
运行结果: