JDK阻塞队列--ArrayBlockingQueue、LinkedBlockingQueue

ArrayBlockingQueue

基本数据结构

  • 数组实现
  • 线程安全保证:ReentrantLock
  • notEmpty等待队列:获取数据的消费者线程被阻塞时放置到该队列
  • notFull等待队列:插入数据的生产者线程被阻塞时放置到该队列

插入数据

public void put(E e) throws InterruptedException {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        //如果当前队列已满,将线程移入到notFull等待队列中
        while (count == items.length)
            notFull.await();
        //满足插入数据的要求时,直接进行入队操作
        enqueue(e);
    } finally {
        lock.unlock();
    }
}

private void enqueue(E x) {
    final Object[] items = this.items;
    //插入数据
    items[putIndex] = x;
    if (++putIndex == items.length)
        putIndex = 0;
    count++;
    //通知消费者线程,当前队列中有数据可供消费
    notEmpty.signal();
}

获取数据

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        //如果队列为空,没有数据,将消费者线程移入等待队列
        while (count == 0)
            notEmpty.await();
        //若队列不为空则获取数据,即完成出队操作dequeue
        return dequeue();
    } finally {
        lock.unlock();
    }
}

private E dequeue() {
    final Object[] items = this.items;
    @SuppressWarnings("unchecked")
    //获取数据
    E x = (E) items[takeIndex];
    items[takeIndex] = null;
    if (++takeIndex == items.length)
        takeIndex = 0;
    count--;
    if (itrs != null)
        itrs.elementDequeued();
    //通知notFull等待队列中的线程,使其由等待队列移入到同步队列中,使其能够有机会获得lock,并执行完成功退出
    notFull.signal();
    return x;
}
  • put、take通过condition通知机制来完成可阻塞的插入和获取数据

LinkedBlockingQueue

  • 与ArrayBlockingQueue主要区别,LinkedBlockingQueue插入和删除时分别由两个lock(takeLock和putLock)控制线程安全,也由这两个lock生成两个对应的condition(notEmpty和notFull)实现可阻塞的插入和删除数据。采用链表来实现队列。

猜你喜欢

转载自blog.csdn.net/weixin_40632321/article/details/88672705