从零开始学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();
    }
}
相关推荐
调试人生的显微镜6 分钟前
深入剖析 iOS 26 系统流畅度,多工具协同监控与性能优化实践
后端
蹦跑的蜗牛7 分钟前
Spring Boot使用Redis实现消息队列
spring boot·redis·后端
非凡ghost15 分钟前
HWiNFO(专业系统信息检测工具)
前端·javascript·后端
非凡ghost18 分钟前
FireAlpaca(免费数字绘图软件)
前端·javascript·后端
ekkcole19 分钟前
java把word转pdf使用jar包maven依赖
java·pdf·word
非凡ghost24 分钟前
Sucrose Wallpaper Engine(动态壁纸管理工具)
前端·javascript·后端
Java小王子呀27 分钟前
Java实现Excel转PDF
java·pdf·excel
间彧28 分钟前
从零到一搭建Spring Cloud Alibbaba项目
后端
楼田莉子29 分钟前
C++学习:C++11关于类型的处理
开发语言·c++·后端·学习
LSTM9733 分钟前
使用 Java 对 PDF 添加水印:提升文档安全与版权保护
后端