实现说明
活动部件是类 BoundedBuffer。
while (items.size() == capacity) notFull.await(); // 已满:挂起生产者等腾位 是唯一的迭代点——其余代码顺序执行一遍。
使用要点
- 跑完文件,输出里会留下标记——
produced item-、taken:。
常见问题
运行「ReentrantLock + Condition 有界缓冲」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 produced item-、taken: 标签标明各步骤。
核心语句
Thread.sleep(50); // 先让缓冲填满:第三个 put 会阻塞在 notFull
System.out.println("taken: " + buffer.take());
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 3; i++) {
buffer.put("item-" + i);
System.out.println("produced item-" + i);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
代码示例
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class BoundedBuffer {
private final Queue<String> items = new ArrayDeque<>();
private final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
private final int capacity;
BoundedBuffer(int capacity) {
this.capacity = capacity;
}
void put(String item) throws InterruptedException {
lock.lock();
try {
while (items.size() == capacity) notFull.await(); // 已满:挂起生产者等腾位
items.add(item);
notEmpty.signal(); // 新元素到达:唤醒挂起的消费者
} finally {
lock.unlock();
}
}
String take() throws InterruptedException {
lock.lock();
try {
while (items.isEmpty()) notEmpty.await(); // 为空:挂起消费者等新元素
String item = items.poll();
notFull.signal();
return item;
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
BoundedBuffer buffer = new BoundedBuffer(2);
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 3; i++) {
buffer.put("item-" + i);
System.out.println("produced item-" + i);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
Thread.sleep(50); // 先让缓冲填满:第三个 put 会阻塞在 notFull
System.out.println("taken: " + buffer.take());
System.out.println("taken: " + buffer.take());
producer.join();
}
}