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

发布于:2024-12-18 ⋅ 阅读:(10) ⋅ 点赞:(0)

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:**生产一个,消费一个

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();

    }
}
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 + "]";
    }
    
}
//生产者线程
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();//唤醒:唤醒对象监视器上任意一个等待的线程
                
            }
        }
    }
    
}
//消费者线程
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();
            }
        }
    }
}

二、⭐️仓储模型

需求:

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

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

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

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 + "]";
	}
}
//仓库类
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;
    }
    
    
}
//生产者线程
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);
        }
    }
}
//消费者线程
public class Consumer extends Thread{
    priate Store store;
    public Consumer(Store store) {
        this.store = store;
    }
    
    @Override
    public void run() {
        while (true) {
            store.pop();
        }
    }
}
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();
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到