LinkedBlockingQueue实现原理
LinkedBlockingQueue
使用链表(单向)完成队列操作的阻塞队列。
它的主要属性如下:
// 容量大小
private final int capacity;
// 元素个数,因为有2个锁,存在竞态条件,使用AtomicInteger
private final AtomicInteger count = new AtomicInteger(0);
// 头结点
private transient Node<E> head;
// 尾节点
private transient Node<E> last;
// 拿锁
private final ReentrantLock takeLock = new ReentrantLock();
// 拿锁的条件对象
private final Condition notEmpty = takeLock.newCondition();
// 放锁
private final ReentrantLock putLock = new ReentrantLock();
// 放锁的条件对象
private final Condition notFull = putLock.newCondition();LinkedBlockingQueue有2个锁(takeLock和putLock),添加数据和删除数据是可以并行进行的,当然添加数据和删除数据的时候只能有1个线程各自执行。
插入元素
offer()方法:如果队列已满,直接返回fasle
抛出IllegalStateException("Queue full")异常;
put()方法:如果队列已满,当前线程会一直阻塞,直到队列中出现空位或响应中断退出
在消费的时候进行唤醒插入阻塞的线程,同时在插入的时候如果容量还没满,也会唤醒插入阻塞的线程
移除元素
poll()方法:如果队列为空,直接返回null
take()方法:如果队列为空,当前线程会一直阻塞,直到队列中有元素插入或响应中断退出;
remove()方法:如果队列为空,则抛出NoSuchElementException异常
Last updated