从零开始学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();
    }
}
相关推荐
zzm6282 分钟前
精读KDD 2017最佳论文:通过类比挖掘加速创新 | 阅读笔记
笔记
你有哈莫吗7 分钟前
CMake构建学习笔记-iconv库的构建
笔记·学习
Mark_ZP9 分钟前
【锁1】Synchronized vs ReentrantLock区别
java
立心者01 小时前
SpringBoot中使用TOTP实现MFA(多因素认证)
java·spring boot·后端
枕星而眠1 小时前
C++ STL Map容器完全指南:从有序红黑树到无序哈希表
java·开发语言
ctlover1 小时前
Python学习第4日
学习
AskHarries1 小时前
SEO 页面怎么生成
后端
爱吃牛肉的大老虎2 小时前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
石榴2 小时前
NestJS 的请求到底经过了什么:装饰器、守卫、拦截器、管道与中间件如何配合
后端
小弥儿2 小时前
GitHub今日热榜 | 2026-08-01:硬件安全工具与AI教育并行
人工智能·学习·开源·github