队列(一):LinkedBlockingQueue

队列(一):LinkedBlockingQueue,第1张

队列(一):LinkedBlockingQueue

linkedBlockingQueue主要方法归类:


linkedBlockingQueue实现了接口中的的三个特性

第一个特性:Queue接口的队列FIFO先进先出特性

    
    boolean add(E e);

    
    boolean offer(E e);

    
    E remove();

    
    E poll();

    
    E element();

    
    E peek();

第二个特性:BlockingQueue接口的阻塞特性

    
    void put(E e) throws InterruptedException;
    
    
    E take() throws InterruptedException;

    
    boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException;

    
    E poll(long timeout, TimeUnit unit)
        throws InterruptedException;

第三个特性:使用Node节点的单向链表特性
不足:链表虽然比数组占用多一点内存空间(可以忽略),链表也无法按索引位置获取元素(队列中中作用不大)。
优点:容量不用预先分配,插入删除节点性能好(删除中间节点不需要移动其他节点)。

    static class Node {
        E item;

        Node next;

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

    
    private final AtomicInteger count = new AtomicInteger();

    
    transient Node head;

    
    private transient Node last;

linkedBlockingQueue的并发特性

linkedBlockingQueue使用了可重入互斥锁ReentrantLock,一是保证并发 *** 作,二是用锁做阻塞等待。

    
    
    private final ReentrantLock takeLock = new ReentrantLock();

    
    
    private final Condition notEmpty = takeLock.newCondition();

    
    
    private final ReentrantLock putLock = new ReentrantLock();

    
    
    private final Condition notFull = putLock.newCondition();

备注:当多个线程按顺序都是takeLock.lock() + takeLock.newCondition().await(),最终多个线程都在等待notify唤醒。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5719916.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存