下面是一个简单的生产者消费者队列:
import java.util.LinkedList;
public class ProducerConsumerQueue<T> {
private final LinkedList<T> queue = new LinkedList<>();
private final int capacity;
public ProducerConsumerQueue(int capacity) {
this.capacity = capacity;
}
public synchronized void put(T element) throws InterruptedException {
while (queue.size() == capacity) {
wait();
}
queue.add(element);
notifyAll();
}
public synchronized T take() throws InterruptedException {
while (queue.size() == 0) {
wait();
}
T element = queue.remove();
notifyAll();
return element;
}
}
该队列使用了一个内部的LinkedList作为存储容器,并提供了put和take方法来实现生产者和消费者的操作。其中,put方法用于向队列中添加元素,如果队列已满,则等待;take方法用于从队列中取出元素,如果队列为空,则等待。
使用该队列的示例代码如下:
public class Main {
public static void main(String[] args) {
ProducerConsumerQueue<String> queue = new ProducerConsumerQueue<>(10);
Thread producerThread = new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
queue.put("element " + i);
System.out.println("Produced: element " + i);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumerThread = new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
String element = queue.take();
System.out.println("Consumed: " + element);
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producerThread.start();
consumerThread.start();
}
}
该示例中,启动了一个生产者线程和一个消费者线程,生产者向队列中添加100个元素,消费者从队列中取出100个元素,并分别输出生产和消费的信息。