学习目标
在并发编程中,阻塞队列在多线程中的场景特别有用,比如在生产和消费者模型中,生产者生产数据到队列,队列满时需要阻塞线程,停止往队列生产。消费者消费队列,对队列为空时阻塞线程停止消费,在Java中有提供不同场景的阻塞队列,那么接下来我们将学习:LinkedBlockingQueue和LinkedBlockingDeque两种阻塞队列。
LinkedBlockingQueue
上次我们学习了基础的有界阻塞队列ArrayBlockingQueue,👉有兴趣可以了解下,明白了有界阻塞队列基本实现原理,而LinkedBlockingQueue与ArrayBlockingQueue比较而言,我们知道ArrayBlockingQueue是通过一个有界的数组对象来存储数据,而LinkedBlockingQueue是用了单链表来实现数据的存储,且相较于ArrayBlockingQueue是用两个锁分别来处理数据的生产和消费。实现类如下:
public class LinkedBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
/** The capacity bound, or Integer.MAX_VALUE if none */
private final int capacity;
/** Current number of elements */
private final AtomicInteger count = new AtomicInteger();
/**
* Head of linked list.
* Invariant: head.item == null
*/
transient Node<E> head;
/**
* Tail of linked list.
* Invariant: last.next == null
*/
private transient Node<E> last;
/** Lock held by take, poll, etc */
private final ReentrantLock takeLock = new ReentrantLock();
/** Wait queue for waiting takes */
private final Condition notEmpty = takeLock.newCondition();
/** Lock held by put, offer, etc */<