java多线程---生产者消费者模式

来源:互联网 发布:linux源码编译mysql 编辑:程序博客网 时间:2024/05/21 18:44

我所理解的生产者消费者模式  : 生产者有物品的时候则等待,没有则生产,生产后,通知消费者,也就是使用notifyall唤醒线程

                                                           消费者有物品则消费,没有就等待,通着生产者生产,唤醒线程

package com.qf.demo;public class Test3 {public static void main(String[] args) {SuperMarket superMarket = new SuperMarket();// FactoryDemo factoryDemo = new FactoryDemo(superMarket);Customer customer = new Customer(superMarket);// Thread thread = new Thread(factoryDemo, "工厂");Thread thread2 = new Thread(customer, "顾客");// thread.start();thread2.start();}}class Bread{int id ;String brand;public Bread(int id, String brand) {super();this.id = id;this.brand = brand;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;}}class  SuperMarket{Bread[] breads = new Bread[6];int index = -1;// 从-1 开始表示什么都没有public synchronized void addBread(Bread bread){if(index>=5){try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}index++;// 给面包数组赋值breads[index] = bread;System.out.println(Thread.currentThread().getName()+"生产了"+bread.getId()+"品牌是"+bread.getBrand()+"下标为"+index);this.notifyAll();}public synchronized void saleBread(){if(index<=-1){try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 需求是打印一下被卖的面包的信息  , 让下标--Bread bread = breads[index];System.out.println(Thread.currentThread().getName()+"卖了"+bread.getId()+"品牌是"+bread.getBrand()+"下标为"+index);// 下标--index--;this.notifyAll();}}class FactoryDemo implements Runnable{// 使用容器类作为属性SuperMarket market;public FactoryDemo(SuperMarket market) {super();this.market = market;}@Overridepublic void run() {for (int i = 0; i < 80; i++) {Bread bread = new Bread(i, Thread.currentThread().getName());market.addBread(bread);}}}class Customer implements Runnable{SuperMarket market;public Customer(SuperMarket market) {super();this.market = market;}@Overridepublic void run() {for (int i = 0; i < 80; i++) {market.saleBread();}}}
创建面包类,超市使用这些面包,超市最多有6个,如果少于6个,则工厂类给予生产,消费者可以购买

0 0
原创粉丝点击