如何使用ReentrantLock和Condition接口实现Java中的生产者消费者模式,并提供相应的代码示例?
时间: 2024-12-07 07:21:01 浏览: 7
在Java中实现生产者消费者模式时,除了传统的`synchronized`和`wait/notify`机制外,还可以利用`ReentrantLock`和`Condition`接口来更精确地控制线程间的协作。这种方式提供了更大的灵活性和更强的功能,允许线程在不同的条件变量上等待,并且可以设置不同的唤醒策略。以下是使用`ReentrantLock`和`Condition`实现生产者消费者模式的示例代码:
参考资源链接:[Java并发编程:线程间通信与协作](https://wenku.csdn.net/doc/1gc523mjtp?spm=1055.2569.3001.10343)
```java
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConsumerExample {
private Queue<Integer> queue = new LinkedList<>();
private int maxSize = 10;
private ReentrantLock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition();
public void produce(int item) throws InterruptedException {
lock.lock();
try {
while (queue.size() == maxSize) {
notFull.await();
}
queue.offer(item);
System.out.printf(
参考资源链接:[Java并发编程:线程间通信与协作](https://wenku.csdn.net/doc/1gc523mjtp?spm=1055.2569.3001.10343)
阅读全文