class MyBlockingQueue {
//这里队列底层用数组实现
private int[] queue = new int[1000];
//创建size变量记录队列现有元素的数量
private int size = 0;
//创建队头指针
private int head = 0;
//创建队尾指针
private int tail = 0;
//创建锁对象
private Object locker = new Object();
//向队列中添加元素,通过加锁操作当队列为满时阻塞,队列不满时才能添加
public void put(int value) throws InterruptedException {
synchronized (locker) {
if (size == queue.length) {
locker.wait();
}
queue[tail] = value;
tail++;
//或者写成tail = tail % queue.length,但在运行性能上CPU执行条件跳转更容易一些,取模操作比较麻烦一些
if (tail >= queue.length) {
tail = 0;
}
size++;
//解除队列为空时等待添加元素的阻塞,解除的是take方法中的wait
locker.notify();
}
}
//出队列,当队列为空时阻塞等待,直到队列中添加了元素
public Integer take() throws Interrupte
Java实现简单的阻塞队列
最新推荐文章于 2025-04-05 21:04:32 发布