生产者消费者模式 用wait/notify实现

该博客展示了如何使用Java实现生产者消费者模型,通过`EventStorage`类利用`LinkedList`作为存储,并用`synchronized`关键字和`wait()`、`notify()`方法协调生产者和消费者的线程同步。`Producer`类负责生产数据,而`Consumer`类则负责消费数据,确保在存储满和空的情况下正确地等待和唤醒线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写仓库

public class EventStorage {

    private Integer maxSize;
    private LinkedList<Date> storage;

    public EventStorage(){
        maxSize=5;
        storage = new LinkedList<>();
    }
    public synchronized void put(){
        while (storage.size() == maxSize){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        storage.add(new Date());
        System.out.println("创库里有了"+storage.size()+"产品");
        notify();//唤醒 沉睡的线程
    }

    public synchronized void take(){
        while (storage.size() ==0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("拿到了:"+storage.poll()+",现在仓库还剩下"+storage.size());
        notify();
    }
}

生产者

public class Producer implements Runnable {

    private EventStorage storage;
    public Producer(EventStorage storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            storage.put();
        }
    }
}

消费者`

public class Consumer implements  Runnable{

    private EventStorage storage;

    public Consumer(EventStorage storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            storage.take();
        }
    }
}

测试

public class App {
    public static void main(String[] args) {
        EventStorage eventStorage = new EventStorage();
        Producer producer =new Producer(eventStorage);
        Consumer consumer = new Consumer(eventStorage);
        Thread thread = new Thread(producer);
        Thread thread1 = new Thread(consumer);
        thread.start();
        thread1.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值