从零开始学Java,学习笔记Day22

Day22

一、⭐️生产者消费者模型

场景:一个生产者线程,一个消费者线程的情况

最终目的:生产一个,消费一个

**需求:**多个线程去操作同一个资源(phone对象)

脏数据:

  • null -- 0.0
  • 华为 mate 70 pro -- 0.0

**需求:**两个产品之间切换生产(目的:放大需求1的问题)

脏数据:

  • null -- 0.0
  • 华为 mate 70 pro -- 0.0
  • 小米 -- 5999
  • 华为 mate 70 pro -- 0.0

**解决方法:**生产者线程必须设置(brand、price)完毕后,消费者线程再执行 -- 加锁

**需求3:**生产一个,消费一个

java 复制代码
public class Test {
    public static void main(String[] args) {
        Phone phone = new Phone();//null -- 0.0
        
        Producer p = new Producer(phone);
        Consumer c = new Consumer(phone);
        
        p.start();
        c.start();

    }
}
java 复制代码
public class Phone {
    
    private String brand;
    private double price;
    private boolean store;
    
    public Phone() {
        
    }
    
    public Phone(String brand, double price) {
        this.brand = brand;
        this.price = price;
    }
    
    public String getBrand() {
        return brand;
    }
    
    public void setBrand(String brand) {
        this.brand = brand;
    }
    
    public double getPrice() {
        return price;
    }
    
    public void setPrice(double price) {
        this.price = price;
    }
    
    public boolean isStore() {
        return store;
    }
    
    public void setStore(boolean store) {
        this.store = store;
    }
    
    public String toString() {
        return "Phone [brand=" + brand + ", price=" + price + "]";
    }
    
}
java 复制代码
//生产者线程
public class Producer extends Thread {
    
    private Phone phone;
    
    public Produce(Phone phone) {
        this.phone = phone;
    }
    
    @Override
    pubic void run() {
        
        boolean flag = true;
        
        while (true) {
            synchronized (phone) {
                if (phone.isStore()) {
                    try {
                        //等待:1.当前线程进入到阻塞状态;2.释放锁资源;3.当前线程记录在对象监视器中
                        phone.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                
                if (flag) {
                    phone.setBrand("华为 mate 70 pro");
                    phone.setPrice(6999);
                } else {
                    phone.setBrand("小米");
                    phone.setPrice(5999);
                }
                phone.setStore(true);
                flag = !flag;
                phone.notify();//唤醒:唤醒对象监视器上任意一个等待的线程
                
            }
        }
    }
    
}
java 复制代码
//消费者线程
public class Consumer {
    private Phone phone;
    
    public Consumer(Phone phone) {
        this.phone = phone;
    }
    
    @Override
    public void run() {
        while (true) {
            synchronized (phone) {
                if (!phone.isStore()) {
                    try {
                        phone.wait();
                    } catch (InterrupterException e) {
                        e.printStackTrace();
                    }
                }
                
                System.out.println(phone.getBrand() + " -- " + phone.getPrice());
                phone.setStore(false);
                phone.notify();
            }
        }
    }
}

二、⭐️仓储模型

需求:

  • 生产者线程不断的生产蛋糕,放入仓库中,仓库的容量可以自行设定
  • 消费者线程不断的消费蛋糕,从仓库中取出,先生产的先卖出

分析:生产者线程类、消费者线程类、仓库类、蛋糕类

场景:多个生产者线程多个消费者线程的情况

java 复制代码
public class Cake {
    private String brand;
    private String datetime;
    	public Cake() {
	}

	public Cake(String brand, String datetime) {
		this.brand = brand;
		this.datetime = datetime;
	}

	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public String getDatetime() {
		return datetime;
	}

	public void setDatetime(String datetime) {
		this.datetime = datetime;
	}

	@Override
	public String toString() {
		return "Cake [brand=" + brand + ", datetime=" + datetime + "]";
	}
}
java 复制代码
//仓库类
public class Store {
    private static final int DEFAULT_INIT_CAPACITY = 5;
    private LinkedList<Cake> list;
    private int currentCapacity;
    private int maxCapacity;
    
    public Store() {
        list = new LinkedList<>();
        maxCapacity = DEFALUT_INIT_CAPACITY;
    }
    
    public store(int capacity) {
        list = new LinkedList<>();
        maxCapacity = capacity;
        
    }
    
    //入库
    public synchronized void push(Cake cake) {
        if (currentCapacity >= maxCapacity) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        currentCapacity++;
        list.add(cake);
        System.out.println("入库,当前容量为:" + currentCapacity);
        notifyAll();
    }
    
    //出库
    public synchronized Cake pop() {
        if (currentCapacity <= 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.ptintStackTrace();
            }
        }
        currentCapacity--;
        Cake cake = list.removeFirst();
        System.out.println("出库,当前容量为:" + currentCapacity + " -- 卖出蛋糕生产日期是:" + cake.getDatetime());
        notifyAll();
        return cake;
    }
    
    
}
java 复制代码
//生产者线程
public class Producer extends Thread {
    private Store store;
    public Produce(Store store) {
        this.store = store;
    }
    
    @Override
    public void run() {
        while (true) {
            Cake cake = new Cake("小米蛋糕", LocalDateTime.now().toString());
            store.push(cake);
        }
    }
}
java 复制代码
//消费者线程
public class Consumer extends Thread{
    priate Store store;
    public Consumer(Store store) {
        this.store = store;
    }
    
    @Override
    public void run() {
        while (true) {
            store.pop();
        }
    }
}
java 复制代码
public class Test {
    public static void main(String[] args) {
        
        Store store = new Store();
        
        Producer p1 = new Producer(store);
        Consumer c1 = new Consumer(store);
        Producer p2 = new Producer(store);
        Consumer c2 = new Consumer(store);
        p1.start();
        c1.start();
        p2.start();
        c2.start();
    }
}
相关推荐
Abelard_3 分钟前
JVM--内存结构
java·开发语言·jvm
JWASX5 分钟前
定时/延时任务-Netty时间轮源码分析
java·netty·定时任务·时间轮
oioihoii14 分钟前
深入解析C++中的函数指针与`typedef`的妙用
java·开发语言·c++
程序猿进阶30 分钟前
Dead Code Clean
java·spring boot·后端·kafka·代码规范·质量管理·代码清理
枫叶落雨22236 分钟前
jdk1.8安装及环境配置(最新最详细教学!!!)
java·jdk1.8
凡人的AI工具箱40 分钟前
每天40分玩转Django:简介和环境搭建
开发语言·后端·python·django·sqlite
不爱运动的跑者2 小时前
全面解析JWT技术
java·web安全
weisian1513 小时前
Redis篇-7--原理篇6--过期机制(定时删除,惰性删除,Redis过期事件监听和Java实现)
java·数据库·redis
禁默3 小时前
JAVA 图形界面编程 AWT篇(1)
java·开发语言
code喵喵4 小时前
系统性能优化
java·性能优化·压力测试