温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

多线程(十九、阻塞队列-LinkedBlockingQueue)

发布时间:2020-07-29 11:50:42 来源:网络 阅读:885 作者:shayang88 栏目:编程语言

LinkedBlockingQueue简介

1、LinkedBlockingQueue底层数据结构基于单链表实现,与ArrayBlockingQueue不同。
2、既可以在初始构造时就指定队列的容量,也可以不指定,如果不指定,那么它的容量大小默认为Integer.MAX_VALUE。
3、区别于ArrayBlockingQueue的全局锁,LinkedBlockingQueue维护了两把锁——takeLock和putLock。
takeLock用于控制出队的并发,putLock用于入队的并发。同一时刻,只能有一个线程能执行入队或者出队操作,但是,入队和出队之间可以并发执行,即同一时刻,可以同时有一个线程进行入队,另一个线程进行出队,这样就可以提升吞吐量。

LinkedBlockingQueue构造

LinkedBlockingQueue使用了一个原子变量AtomicInteger记录队列中元素的个数,以保证入队/出队并发修改元素时的数据一致性

public class LinkedBlockingQueue<E> extends AbstractQueue<E>
    implements BlockingQueue<E>, java.io.Serializable {

    /**
     * 队列容量.
     * 如果不指定, 则为Integer.MAX_VALUE
     */
    private final int capacity;

    /**
     * 队列中的元素个数,原子类时间并发
     */
    private final AtomicInteger count = new AtomicInteger();

    /**
     * 队首指针.
     * head.item == null
     */
    transient Node<E> head;

    /**
     * 队尾指针.
     * last.next == null
     */
    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();

    /**
     * 链表结点定义
     */
    static class Node<E> {
        E item;

        Node<E> next;   // 后驱指针

        Node(E x) {
            item = x;
        }
    }

}

主要方法:

1、插入元素-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上等待
            notFull.await();
        }
        enqueue(node);                      // 将新结点链接到“队尾”

        /**
         * c+1 表示的元素个数.
         * 如果,则唤醒一个“入队线程”
         */
        c = count.getAndIncrement();        // c表示入队前的队列元素个数
        if (c + 1 < capacity)               // 入队后队列未满, 则唤醒一个“入队线程”
            notFull.signal();
    } finally {
        putLock.unlock();
    }

    if (c == 0)                             // 队列初始为空, 则唤醒一个“出队线程”
        signalNotEmpty();
}

注意点:
1、每入队一个元素后,如果队列还没满,则需要唤醒其它可能正在等待的“入队线程”
2、每入队一个元素,都要判断下队列是否空了,如果空了,说明可能存在正在等待的“出队线程”,后面来的出队线程也会进行无用的等待,所以需要唤醒它,提升性能。
3、入队元素后,避免直接尝试唤醒出队线程,否则会要求去拿出队锁,这样持有锁A的同时,再去尝试获取锁B,很可能引起死锁

2、删除元素-take

/**
 * 从队首出队一个元素
 */
public E take() throws InterruptedException {
    E x;
    int c = -1;
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;   // 获取“出队锁”
    takeLock.lockInterruptibly();
    try {
        while (count.get() == 0) {                  // 队列为空, 则阻塞线程
            notEmpty.await();
        }
        x = dequeue();
        c = count.getAndDecrement();                // c表示出队前的元素个数
        if (c > 1)                                  // 出队前队列非空, 则唤醒一个出队线程
            notEmpty.signal();
    } finally {
        takeLock.unlock();
    }
    if (c == capacity)                              // 队列初始为满,则唤醒一个入队线程
        signalNotFull();
    return x;
}
/**
 * 队首出队一个元素.
 */
private E dequeue() {
    Node<E> h = head;
    Node<E> first = h.next;
    h.next = h;         // help GC
    head = first;
    E x = first.item;
    first.item = null;
    return x;
}

注意点:
1、每出队一个元素前,如果队列非空,则需要唤醒其它可能正在等待的“出队线程”
2、每出队一个元素,都要判断下队列是否满,如果是满的,说明可能存在正在等待的“入队线程”,需要唤醒它

总结:

1、队列大小不同。ArrayBlockingQueue初始构造时必须指定大小,而LinkedBlockingQueue构造时既可以指定大小,也可以不指定(默认为Integer.MAX_VALUE);
2、底层数据结构不同。ArrayBlockingQueue底层采用数组作为数据存储容器,而LinkedBlockingQueue底层采用单链表作为数据存储容器;
3、两者的加锁机制不同。ArrayBlockingQueue使用一把全局锁,即入队和出队使用同一个ReentrantLock锁;而LinkedBlockingQueue进行了锁分离,入队使用一个ReentrantLock锁(putLock),出队使用另一个ReentrantLock锁(takeLock);
4、LinkedBlockingQueue不能指定公平/非公平策略(默认都是非公平),而ArrayBlockingQueue可以指定策略。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI