假设有一个生产者-消费者场景,使用 ReentrantLock 和 Condition 实现一个线程安全的缓冲区,如何处理多个消费者等待生产者生产的情况?

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadSafeBuffer {
    private final Queue<Integer> buffer;
    private final int capacity;
    private final Lock lock;
    private final Condition notFull;
    private final Condition notEmpty;

    public ThreadSafeBuffer(int capacity) {
        this.buffer = new LinkedList<>();
        this.capacity = capacity;
        this.lock = new ReentrantLock();
        this.notFull = lock.newCondition();
        this.notEmpty = lock.newCondition();
    }

    // 生产者方法
    public void produce(int item) throws InterruptedException {
        lock.lock();
        try {
            // 缓冲区满时,生产者等待
            while (buffer.size() == capacity) {
                notFull.await();
            }
            buffer.add(item);
            System.out.println("生产者生产: " + item);
            // 唤醒所有等待的消费者
            notEmpty.signalAll();
        } finally {
            lock.unlock();
        }
    }

    // 消费者方法
    public int consume() throws InterruptedException {
        lock.lock();
        try {
            // 缓冲区空时,消费者等待
            while (buffer.isEmpty()) {
                notEmpty.await();
            }
            int item = buffer.poll();
            System.out.println("消费者消费: " + item);
            // 唤醒所有等待的生产者
            notFull.signalAll();
            return item;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ThreadSafeBuffer buffer = new ThreadSafeBuffer(5);

        // 生产者线程
        Thread producer = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    buffer.produce(i);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 消费者线程
        Thread consumer1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    buffer.consume();
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread consumer2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    buffer.consume();
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();
        consumer1.start();
        consumer2.start();
    }
}

实现说明

  1. 缓冲区的线程安全实现:

    • 使用 ReentrantLock 和两个 Condition(notFull 和 notEmpty)来管理生产者和消费者的等待条件。
    • notFull 表示缓冲区未满的条件,当缓冲区满时,生产者会等待。
    • notEmpty 表示缓冲区非空的条件,当缓冲区空时,消费者会等待。
  2. 生产者的逻辑:

    • 生产者首先获取锁,检查缓冲区是否已满。如果满了,调用 notFull.await() 进入等待状态。
    • 当缓冲区未满时,生产者将数据放入缓冲区,并通过 notEmpty.signalAll() 唤醒所有等待的消费者。
  3. 消费者的逻辑:

    • 消费者获取锁后,检查缓冲区是否为空。如果为空,调用 notEmpty.await() 进入等待状态。
    • 当缓冲区非空时,消费者取出数据,并通过 notFull.signalAll() 唤醒所有等待的生产者。
  4. 多个消费者的处理:

    • 通过 notEmpty.signalAll(),可以唤醒多个等待的消费者线程,确保缓冲区中的数据被及时消费。
    • 示例中启动了两个消费者线程 consumer1 和 consumer2,模拟多个消费者并发消费的场景。

示例输出

运行程序后,可以看到生产者和消费者的交替执行情况。例如:

生产者生产: 0
消费者消费: 0
生产者生产: 1
消费者消费: 1
生产者生产: 2
消费者消费: 2
...

注意事项

  1. 使用 while 循环而非 if 判断条件,避免虚假唤醒问题。
  2. 在 finally 块中释放锁,确保锁一定会被释放。
  3. signalAll() 唤醒所有等待线程,适用于多个消费者或生产者的场景。