队列 通常来说 是 一种 first in first out 的数据结构 ,也就是 先进先出 FIFO
Queue
在接口中规定了以下6中方法,add继承 Collection
add 和 offer 添加元素至队列的尾部
remove 和 poll 取出队列的第一个位置元素
element 和 peek 是 检索队列第一个位置是否有元素
add offer 和 put的异同
LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
queue.add(1);
queue.put(2);
queue.offer(3);
System.out.println(queue);
输出结果 [1, 2, 3]
可以看到put方法会阻塞直到空间可用。
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly();
try {
while (count.get() == capacity) {
notFull.await();
}
enqueue(node);
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
阻塞队列
新增方法
Deque
两端队列
ArrayBlockingQueue
add
offer
add 封装了 offer ,如果元素放不进去,则抛出异常。
checkNotNull
poll
remove
remove 封装了poll,如果元素取不出来抛出异常
peek
element
element 封装了 peek 如果 检索不到元素则抛出异常
take
put
take 和 put 则是如果取不出来或者放不进去则一直等待。