import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class BoundedBlockingQueue {
private AtomicInteger size = new AtomicInteger(0);
private static final ReentrantLock lock = new ReentrantLock();
private final Condition isEmpty = lock.newCondition();
private final Condition isFull = lock.newCondition();
private final LinkedList<Integer> list = new LinkedList<Integer>();
private final int capacity;
public BoundedBlockingQueue(int capacity) {
this.capacity = capacity;
}
public void enqueue(int element) throws InterruptedException {
lock.lock();
try {
while (size.get() == capacity) {
isFull.await();
}
list.addFirst(element);
size.incrementAndGet();
isEmpty.signal();
} finally {
lock.unlock();
}
}
public int dequeue() throws InterruptedException {
lock.lock();
try{
while(size.get() == 0){
isEmpty.await();
}
int last = list.getLast();
list.removeLast();
size.decrementAndGet();
isFull.signal();
return last;
} finally {
lock.unlock();
}
}
public int size() {
return size.get();
}
}
Leetcode_1188_设计有限阻塞队列_多线程
最新推荐文章于 2024-10-16 21:17:27 发布
这个博客展示了如何使用Java实现一个基于`ReentrantLock`和`Condition`的有界阻塞队列BoundedBlockingQueue。队列容量可定制,支持`enqueue`和`dequeue`操作,遵循先进先出原则,当队列满或空时,操作会等待条件满足后再进行。

1237

被折叠的 条评论
为什么被折叠?



