1.队列的基本知识
和栈相反,队列是一种先进先出(First In First Out,缩写为FIFO)的线性表,它只允许一端进行插入,而在另外一端删除元素。这和我们日常生活中的排队是一致的,最早进入队列的元素最早离开。在队列中,允许插入的一端叫做队尾(rear),允许删除的一端称之为队头(front)。
2.队列的基本操作
InitQueue:构造一个空队列
DestroyQueue:销毁队列
ClearQueue:清空队列
QueueEmpty:判断队列是否为空
QueueLength:队列长度
GetHead:获取队列头部元素
EnQueue:入列
DeQueue:出列
3.java中阻塞队列 - ArrayBlockingQueue 的实现
阻塞队列的概念是,一个指定长度的队列,如果队列满了,添加新元素的操作会被阻塞等待,直到有空位为止。同样,当队列为空时候,请求队列元素的操作同样会阻塞等待,直到有可用元素为止。
利用数组来实现阻塞队列
/**
*初始化一个长度为capacity的数组
*采用非公平策略:让线程自由竞争锁,不保证等待最长的线程优先获取锁
*采用公平策略:让等待时间最长的线程优先获取锁
*/
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
/**
*出列:
*将数组的中第一个有值的元素至空
*如果数组元素的实际长度为0,则等待
*直到获得通知
*/
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == 0)
notEmpty.await();
} catch (InterruptedException ie) {
notEmpty.signal(); // propagate to non-interrupted thread
throw ie;
}
E x = extract();
return x;
} finally {
lock.unlock();
}
}
/**
*入列:
*将新的元素插入队尾
*如果队列已满,则等待
*
*/
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
final E[] items = this.items;
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == items.length)
notFull.await();
} catch (InterruptedException ie) {
notFull.signal(); // propagate to non-interrupted thread
throw ie;
}
insert(e);
} finally {
lock.unlock();
}
}
/**
*获取队列头元素
*
*/
public E peek() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (count == 0) ? null : items[takeIndex];
} finally {
lock.unlock();
}
}
/*
*获取队列长度
*
*/
public int size() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
4.Sample