JDK源码分析之主要阻塞队列实现类LinkedBlockingQueue

LinkedBlockingQueue类的继承树:

LinkedBlockingQueue   继承 AbstractQueue  继承  AbstractCollection 实现 Collection

LinkedBlockingQueue   实现   BlockingQueue  实现了Queue 实现了 Collection  


LinkedBlockingQueue类实现了BlockingQueue 阻塞队列接口,BlockingQueue继承的是Queue接口

BlockingQueue接口声明的主要方法:

添加元素:

boolean add(E e); //添加元素进队列,添加成功返回true

boolean offer(E e);//添加元素进队列,添加成功返回true,添加失败返回false;

void put(E e) ;//添加元素如队列,容量满了线程发生阻塞,知道容量有空间。

        第三个方法才是我要着重分析的,这个方法实现了队列的阻塞功能。

删除元素:

E poll(long timeout, TimeUnit unit) //删除队列头部元素,如果队列为空,返回null,否则返回元素;
boolean remove(Object o);//基于对象找到对应的元素,并删除。删除成功返回true,否则返回false;
E take();//删除头部 元素,如果队列为空,一直阻塞到队列有元素并删除。

LinkedBlockingQueue的行为集已经在BlockingQueue接口中定义了主要部分,其他的行为都是属于集合类的方法。在java的许多继承树类集合定义了许多方

法,这些方法按我个人理解,可以分为两种类型,一种是必须在实现类中才能实现的,另一种是在抽象类中就能够实现的,这两种类型的方法,后者是依赖前者的,在抽象类中

实现的方法相当于更高层次的行为,这些行为依赖同一层的其他抽象未实现的方法,未实现的抽象方法下层到实现类中去完成。


BlockingQueue类实现链表的链表类和节点类

         LinkedBlockingQueue类实现的是数据结构是链表,链表节点类Node 的类声明如下

class   Node{

E item;

Node<E> next;

}

实现的链表为单向链表。

链表类源码:

class LinkedBlockingQueue{

int  capacity;//单向链表容量

Node<E> head;//链表表头

Node<E> last;//链表表尾

 private final AtomicInteger count = new AtomicInteger(0);//链表中元素数量

//同步锁工具--拿锁

private final ReentrantLock takeLock = new ReentrantLock();

//拿锁条件对象

private final Condition notEmpty = takeLock.newCondition();

//同步锁工具--放锁
private final ReentrantLock putLock = new ReentrantLock();

//放锁条件对象

private final Condition notFull = putLock.newCondition();

}

这个阻塞队列使用的多线程同步工具和ArrayBlockingQueue类一样,也是ReentrantLock。

单向链表模型图如下:


队列链表类LinkedBlockingQueue的入列和出列的底层方法是enqueue和dequeue。这两个方法比较好容易理解

  private void enqueue(Node<E> node) {
        // assert putLock.isHeldByCurrentThread();
        // assert last.next == null;
        last = last.next = node;//每个插入链表的节点都会放到尾部,并将last引用指向最后一个节点
    }
对列的出列是发生在对列的头部

  /*
     * OPERATION:对列出列操作
     * LOGIC:返回的值是head指向空Node的下一个Node的item值,将这个Node的item赋为空值,并使head指向这个Node;
     * 
     */
    private E dequeue() {
        // assert takeLock.isHeldByCurrentThread();
        // assert head.item == null;
        Node<E> h = head;
        Node<E> first = h.next;
        h.next = h; // help GC//设置h的next应用指向本身对象,和其他对象没有任何关系,方便GC回收
        head = first;//head指向下一个节点,但是此类的链表的head节点是为空的,所以:
        E x = first.item;//返回队列元素值
        first.item = null;//将头节点置为空节点null
        return x;
    }

链表的各种版本的出列和入列操作底层操作都是要调用上面两种方法的,类对出列操作和入列操作使用了两个锁进行同步,每个同步锁都各自对应了一个获取相应锁后的一

个阻塞条件,其中类还有一系列操作需要同时获取两种锁。

put方法

    public void put(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException();//e为空,抛出空指针异常
        // Note: convention in all put/take/etc is to preset local var
        // holding count negative to indicate failure unless set.
        int c = -1;
        Node<E> node = new Node(e);
        final ReentrantLock putLock = this.putLock;//获取入列操作锁
        final AtomicInteger count = this.count;//队列元素个数
        putLock.lockInterruptibly();//入列锁关锁
        try {
            /*
             * Note that count is used in wait guard even though it is
             * not protected by lock. This works because count can
             * only decrease at this point (all other puts are shut
             * out by lock), and we (or some other waiting put) are
             * signalled if it ever changes from capacity. Similarly
             * for all other uses of count in other wait guards.
             */
            while (count.get() == capacity) {//如果队列满了,则在入列锁条件这阻塞,直到队列为非满状态
                notFull.await();
            }
            enqueue(node);//入列操作
            c = count.getAndIncrement();//元素个数加一
            if (c + 1 < capacity)//
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
    }
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();//队列元素个数减一
            if (c > 1)
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)
            signalNotFull();
        return x;
    }
remove就是其中一种获取两把锁的方法

  public boolean remove(Object o) {
        if (o == null) return false;
        fullyLock();//获取入列和出列两把锁
        try {
            for (Node<E> trail = head, p = trail.next;
                 p != null;
                 trail = p, p = p.next) {
                if (o.equals(p.item)) {
                    unlink(p, trail);
                    return true;
                }
            }
            return false;
        } finally {
            fullyUnlock();//释放锁
        }
    }

LinkedBlockingQueue类是一个同步类,用于消息队列的开发,它是一个单向链表,数据结构是队列,出列发生在链表尾部,入列发生在队列头部,头部节点为空节点。

该类经常用于多线程编程的开发,用于线程之间的数据交换。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

比特科技软件开发工作室

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值