leetcode 阻塞队列
package com.xkl.week2;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
//阻塞队列,应该设计为循环队列
public class MyBlockingQueue {
// 插入位置
int enIndex;
// 弹出位置
int deIndex;
ReentrantLock lock;
Condition notFullCondition;
Condition notEmptyCondition;
//元素实际所在位置
final Integer[] objs;
//当前元素数量
Integer capacity;
//构造,初始化两个条件
public MyBlockingQueue(int size) {
notFullCondition = lock.newCondition();
notEmptyCondition = lock.newCondition();
objs = new Integer[size];
}
//插入元素,满则阻塞
public void insertTail(int element) throws InterruptedException {
try {
//获取资源的锁
lock.lock();
//循环判断,满容量的时候,进入await();await 会释放掉锁
while (capacity == objs.length) {
notFullCondition.await();
}
objs[enIndex++] = element;
//增加当前容量
capacity ++;
//唤醒非空条件
notEmptyCondition.signalAll();
if (enIndex >= capacity) {
enIndex = 0;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//解锁
lock.unlock();
}
}
//头部弹出元素,空则阻塞, 信号量可以实现类似于条件等待的效果吗,即信号量满足的时候,则阻塞该线程,直到信号量减少,说明有新元素被插入了。
public Integer getHead() {
try {
lock.lock();
while(capacity ==0){
notEmptyCondition.await();
}
Integer element = objs[deIndex];
objs[deIndex] = null;
deIndex ++;
//容量减少
capacity --;
//唤醒 非满条件
notFullCondition.signalAll();
if (deIndex >= capacity) {
deIndex = 0;
}
return element;
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
return null;
}
//判断非空
public boolean isEmpty(){
return capacity == 0;
}
//判断满了
public boolean isFull(){
return capacity == objs.length;
}
}