一、阻塞队列说明
ArrayBlockingQueue是个底层以数组实现为基础的阻塞队列,由于该阻塞队列的构造函数中都有capacity,所以它是一个有界阻塞队列。
常用方法和区别如下:
抛出异常 | 特殊值 | 阻塞 | |
插入 |
// 放入元素,如果队列满了,则抛出异常 public boolean add(E e) { return super.add(e); } public boolean add(E e) { 真正调用的是父类AbstractQueue.add(E e)方法 |
public boolean offer(E e) { checkNotNull(e); |
public void put(E e) throws InterruptedException { checkNotNull(e); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (count == items.length) notFull.await(); enqueue(e); } finally { lock.unlock(); } } 如果队列满了,则阻塞等待 |
移除 |
public E remove() { E x = poll(); if (x != null) return x; else throw new NoSuchElementException(); } 如果队列为空,则抛NoSuchElementException(); |
public E poll() { final ReentrantLock lock = this.lock; lock.lock(); try { return (count == 0) ? null : dequeue(); } finally { lock.unlock(); } } 如果队列为空,返回null |
public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (count == 0) notEmpty.await(); return dequeue(); } finally { lock.unlock(); } } 如果队列为空,则阻塞等待 |
读取 |
public E element() { E x = peek(); if (x != null) return x; else throw new NoSuchElementException(); } 如果对列为空,则抛NoSuchElementException(); |
public E peek() { final ReentrantLock lock = this.lock; lock.lock(); try { return itemAt(takeIndex); // null when queue is empty } finally { lock.unlock(); } } 队列为空,返回null |
不可用 |
上述3个方法在AbstractQueue中 | 上述3个方法在ArrayBlockingQueue中 | 底层使用了Condition队列 |