缓冲区法简单实现生产消费模式

缓冲区法 生产者 消费者 产品 容器

public class TestTwo {
    // 生产者  消费者  容器  产品
    public static void main(String[] args) {
        Home home = new Home();
        new Thread(new Productor(home)).start();
        new Thread(new Consumor(home)).start();
    }

}
// 生产者
class Productor extends Thread{
    Home home;
    public Productor(Home home){this.home = home;}
    // 生产方式
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            home.push(new Dog(i));
        }
    }
}
// 消费者
class Consumor extends Thread{
    Home home;
    public Consumor(Home home){this.home = home;}
    // 生产方式
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            home.pop();
        }
    }
}
// 容器
@Data
class Home{
    // 容量  最多10个
    Dog[] dogs = new Dog[10];
    // 计数器
    int count = 0;
    // 生产者向里面加产品
    public synchronized void push(Dog dog){
        // 满了,等待
        if(dogs.length == count){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("生产了第" +dog.id + "只");
        dogs[count] = dog;
        count++;
        // 有生产那就通知消费
        notifyAll();
    }
    // 消费者消费产品
    public synchronized  void pop(){
        // 没了,等待
        if(count == 0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Dog dog = dogs[count];
        System.out.println("吃掉了第" +dog.id + "只");
        // 有消费那就通知生产
        notifyAll();
    }

}
// 产品
@Data
class Dog{
    int id;
    public Dog(int id) {
        this.id = id;
    }
}

posted @ 2022-01-04 01:10  窃窃私语QAQ  阅读(34)  评论(0编辑  收藏  举报