java使用Lock锁实现生产者队列和消费者队列 相互唤醒沉睡的线程同步案例
时间: 2024-03-18 10:15:54 浏览: 93
Java基于Lock的生产者消费者模型示例
下面是一个使用Lock锁实现生产者队列和消费者队列的相互唤醒沉睡的线程同步案例:
```java
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 ProducerConsumerLockExample {
private static final int CAPACITY = 5;
private final Queue<Integer> queue = new LinkedList<>();
private final Lock lock = new ReentrantLock();
private final Condition notEmpty = lock.newCondition();
private final Condition notFull = lock.newCondition();
public static void main(String[] args) {
ProducerConsumerLockExample example = new ProducerConsumerLockExample();
Thread producer = new Thread(() -> {
try {
example.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread consumer = new Thread(() -> {
try {
example.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
producer.start();
consumer.start();
}
private void produce() throws InterruptedException {
while (true) {
lock.lock();
try {
while (queue.size() == CAPACITY) {
System.out.println("Queue is full, waiting");
notFull.await();
}
int value = (int) (Math.random() * 100);
System.out.println("Produced " + value);
queue.add(value);
notEmpty.signalAll();
} finally {
lock.unlock();
}
}
}
private void consume() throws InterruptedException {
while (true) {
lock.lock();
try {
while (queue.isEmpty()) {
System.out.println("Queue is empty, waiting");
notEmpty.await();
}
Integer value = queue.remove();
System.out.println("Consumed " + value);
notFull.signalAll();
} finally {
lock.unlock();
}
}
}
}
```
在该示例中,我们创建了一个具有固定容量的队列,当生产者向队列添加元素时,如果队列已满,则生产者线程会等待,直到消费者消耗了一些元素并释放了空间。另一方面,当消费者从队列中删除元素时,如果队列为空,则消费者线程将等待,直到生产者添加了一些元素并通知消费者。
这里使用了Lock锁和Condition对象来实现线程同步。其中,notEmpty和notFull条件变量分别用于通知消费者队列非空和生产者队列非满。当队列为空时,消费者线程调用notEmpty.await()方法来等待;当队列已满时,生产者线程调用notFull.await()方法来等待。当生产者向队列中添加元素时,调用notEmpty.signalAll()方法来通知消费者队列非空;当消费者从队列中删除元素时,调用notFull.signalAll()方法来通知生产者队列非满。
阅读全文