如何设计一个线程安全的队列类,使其能够满足生产者-消费者模型的需求?

要设计一个线程安全的队列类以满足生产者-消费者模型的需求,可以使用 Java 提供的并发工具类或手动实现同步机制。以下是两种常见的实现方式:

### 1. 使用 `BlockingQueue` 接口的实现类
`BlockingQueue` 是一个线程安全的队列接口,Java 提供了多种实现类,例如 `ArrayBlockingQueue` 和 `LinkedBlockingQueue`。这些实现类内部已经实现了线程安全的机制,可以直接用于生产者-消费者模型。

**示例代码:**
```java
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerConsumerExample {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);

        // 生产者线程
        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 20; i++) {
                    queue.put(i); // 阻塞直到队列有空位
                    System.out.println("Produced: " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // 消费者线程
        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 20; i++) {
                    int value = queue.take(); // 阻塞直到队列有元素
                    System.out.println("Consumed: " + value);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}

说明:

  • put 方法在队列满时会阻塞,直到有空位。
  • take 方法在队列空时会阻塞,直到有元素。
  • LinkedBlockingQueue 是无界队列的默认实现,但可以指定容量以限制队列大小。

2. 手动实现线程安全的队列

如果希望手动实现线程安全的队列,可以使用 synchronized 关键字或 ReentrantLock 来同步访问共享资源。此外,可以使用 wait 和 notify 机制实现生产者和消费者的协作。

示例代码:

import java.util.LinkedList;
import java.util.Queue;

public class ManualThreadSafeQueue<T> {
    private final Queue<T> queue = new LinkedList<>();
    private final int maxSize;

    public ManualThreadSafeQueue(int maxSize) {
        this.maxSize = maxSize;
    }

    public synchronized void put(T item) throws InterruptedException {
        while (queue.size() == maxSize) {
            wait(); // 队列满时等待
        }
        queue.add(item);
        notifyAll(); // 唤醒等待的消费者
    }

    public synchronized T take() throws InterruptedException {
        while (queue.isEmpty()) {
            wait(); // 队列空时等待
        }
        T item = queue.poll();
        notifyAll(); // 唤醒等待的生产者
        return item;
    }
}

说明:

  • 使用 synchronized 关键字确保操作的原子性。
  • wait 和 notifyAll 用于线程间协作:生产者在队列满时等待,消费者在队列空时等待。
  • 手动实现时需要处理线程的虚假唤醒问题(while 循环检查条件)。

总结

选择哪种实现方式取决于具体需求:

  1. BlockingQueue 实现类:简单高效,适合大多数场景。
  2. 手动实现:灵活性更高,适合需要定制化同步逻辑的场景。

不管是哪种方式,都需要确保队列的线程安全性,避免死锁或性能问题。