从零开始学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();
    }
}
相关推荐
我的xiaodoujiao22 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 38--Allure 测试报告
python·学习·测试工具·pytest
一 乐6 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
好奇龙猫6 小时前
【AI学习-comfyUI学习-第三十节-第三十一节-FLUX-SD放大工作流+FLUX图生图工作流-各个部分学习】
人工智能·学习
Boilermaker19926 小时前
[Java 并发编程] Synchronized 锁升级
java·开发语言
saoys7 小时前
Opencv 学习笔记:图像掩膜操作(精准提取指定区域像素)
笔记·opencv·学习
Cherry的跨界思维7 小时前
28、AI测试环境搭建与全栈工具实战:从本地到云平台的完整指南
java·人工智能·vue3·ai测试·ai全栈·测试全栈·ai测试全栈
alonewolf_997 小时前
JDK17新特性全面解析:从语法革新到模块化革命
java·开发语言·jvm·jdk
一嘴一个橘子7 小时前
spring-aop 的 基础使用(啥是增强类、切点、切面)- 2
java
码事漫谈7 小时前
Protocol Buffers 编码原理深度解析
后端
sheji34167 小时前
【开题答辩全过程】以 中医药文化科普系统为例,包含答辩的问题和答案
java