实现生产者和消费者模式简介

本文介绍使用synchronized和Lock实现生产者消费者模式的两种方法。通过具体代码示例展示了如何利用线程间的等待与通知机制来解决缓冲区同步问题。

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

1、synchronized 实现

public class ProducerConsumerDemo <T>{
    LinkedList<T> list = new LinkedList<T>();
    final int MAX = 10;
    int count = 0;
    public synchronized void put(T t){
        // 为什么用while而不是if,能否还原错误场景
        while(list.size() == MAX){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        list.add(t);
        ++count;
        this.notifyAll();
    }
    public synchronized T get(){
        T t = null;
        while(list.size() == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        t = list.removeFirst();
        count--;
        this.notifyAll();
        return t;
    }

    public static void main(String[] args) {
        ProducerConsumerDemo t = new ProducerConsumerDemo();
        for (int i = 0; i < 2; i++) {
            new Thread(()->{
                for (int j = 0; j < 25; j++) {
                    t.put(Thread.currentThread().getName() + " " + j);
                }
            },"p" + i).start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                for (int j = 0; j < 10; j++) {
                    System.out.println(t.get());
                }
            },"c" + i).start();
        }
    }
}

备注:先跑消费者,当生产者和消费组线程数达到一定数量时,t = list.removeFirst(); 执行报错,

           notifyAll() 唤醒的是所有线程,同一个对象同一时刻只能有一个线程拿到锁,若消费者线程拿到锁以后不判断是否有元素,则程序一直往下走,容易报错。

2、Lock 实现

public class LockProducerConsumerDemo<T> {
    LinkedList<T> list = new LinkedList<T>();
    final int MAX = 10;
    int count = 0;
    Lock lock = new ReentrantLock();
    Condition producer = lock.newCondition();
    Condition consumer = lock.newCondition();
    public void put(T t){
        try{
            lock.lock();
            while(list.size() == MAX){
                producer.await();
            }
            list.add(t);
            ++count;
            consumer.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public T get(){
        T t = null;
        try{
            lock.lock();
            while(list.size() == 0){
                consumer.await();
            }
            t = list.removeFirst();
            count--;
            producer.signalAll();
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
        return t;
    }

    public static void main(String[] args) {
        LockProducerConsumerDemo t = new LockProducerConsumerDemo();
        for (int i = 0; i < 2; i++) {
            new Thread(()->{
                for (int j = 0; j < 25; j++) {
                    t.put(Thread.currentThread().getName() + " " + j);
                }
            },"p" + i).start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                for (int j = 0; j < 10; j++) {
                    System.out.println(t.get());
                }
            },"c" + i).start();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值