美文网首页
LinkedBlockingQueue (笔记)

LinkedBlockingQueue (笔记)

作者: 红鲤鱼与绿鲤鱼与驴与鱼 | 来源:发表于2022-03-30 20:38 被阅读0次

    1.概述

    LinkedBlockingQueue 队列是一个单链表结构、阻塞的队列。他的存(put、offer)取(take、poll、peek、remove)方法都使用了ReentrantLock进行加锁操作,所以他是线程安全的

      private final ReentrantLock takeLock = new ReentrantLock();
    
        /** Wait queue for waiting takes */
        private final Condition notEmpty = takeLock.newCondition();
    
        /** Lock held by put, offer, etc */
        private final ReentrantLock putLock = new ReentrantLock();
    
        /** Wait queue for waiting puts */
        private final Condition notFull = putLock.newCondition();
    

    2.构造方法

    LinkedBlockingQueue 有三个构造方法 LinkedBlockingQueue(),LinkedBlockingQueue(int capacity),LinkedBlockingQueue(int capacity)

        //默认设置的容量为Integer.MAX_VALUE
        public LinkedBlockingQueue() {
            this(Integer.MAX_VALUE);
        }
        //可以自行指定容量大小
        public LinkedBlockingQueue(int capacity) {
            if (capacity <= 0) throw new IllegalArgumentException();
            this.capacity = capacity;
            last = head = new Node<E>(null);
        }
        //可以传入一个容器如(ArrayList、ArraySet等;注意Map不行,Map没有实现Collection接口)
        public LinkedBlockingQueue(Collection<? extends E> c) {
            this(Integer.MAX_VALUE);
            final ReentrantLock putLock = this.putLock;
            //加锁
            putLock.lock(); // Never contended, but necessary for visibility
            try {
                int n = 0;
                for (E e : c) {
                    if (e == null)
                        throw new NullPointerException();
                    if (n == capacity)
                        throw new IllegalStateException("Queue full");
                    //存入到队列中
                    enqueue(new Node<E>(e));
                    ++n;
                }
                count.set(n);
            } finally {
                //释放锁
                putLock.unlock();
            }
        }
    

    3.存取数据方法

    3.1 存数据的方法
    • put()   阻塞,无返回值,在队尾插入数据,如果队列满了就会一直等,直到空间可用
    • offer()   非阻塞, 有返回值,在队尾插入数据,如果队列满了就直接返回false
    • add()   非阻塞,有返回值,内部调用的offer,但是如果添加失败就抛异常(如果需要返回值推荐使用offer)
    3.2取数据的方法
    • take()    阻塞,从队列头部获取元素,并删除。当队列为空时阻塞,直到有数据存进来
    • poll()  非阻塞,从队列头部获取元素,并删除。当队列为空时返回null
    • peek()  非阻塞,从队列头部获取元素,不删除。当队列为空时返回null
    3.3 移除元素
    • remove() 移除队列中某个元素

    源码

    简单的看两个源码put()poll() 其他的原理都是一样,可自行查看

    put()方法,阻塞,无返回值

    public void put(E e) throws InterruptedException {
            //如果元素为null抛出异常,可见LinkedBlockingQueue是不可以存null的
            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.await();
                }
              //加入到队列,加到队尾
                enqueue(node);
              //数量+1
                c = count.getAndIncrement();
              //唤醒等待的线程,不好解释可以看一下signal()注释就明白了
                if (c + 1 < capacity)
                    notFull.signal();
            } finally {
                //释放锁
                putLock.unlock();
            }
            if (c == 0)
                signalNotEmpty();
        }
    

    poll() 弹出顶部元素

    public E poll() {
            final AtomicInteger count = this.count;
            //如果队列没有数据,则返回null
            if (count.get() == 0)
                return null;
            E x = null;
            int c = -1;
            final ReentrantLock takeLock = this.takeLock;
          //加锁
            takeLock.lock();
            try {
                if (count.get() > 0) {
                    //获取队列中第一个元素,这个方法里面有点意思(利用垃圾回收算法让对象回收,可达性算法)
                    x = dequeue();
                    c = count.getAndDecrement();
                    if (c > 1)
                        notEmpty.signal();
                }
            } finally {
                //释放锁
                takeLock.unlock();
            }
            if (c == capacity)
                signalNotFull();
            return x;
        }
    

    上面两个方法一个放入一个取出,其他的方法基本都差不多
    接下来看一下这个方法dequeue(),这个方法就是获取到队列的第一个元素

        private E dequeue() {
            // assert takeLock.isHeldByCurrentThread();
            // assert head.item == null;
            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;
        }
    

    上面有这么一行代码h.next = h; // help GC当时没看明白这个注释,后来才明白这是利用垃圾回收算法中可达性算法来对这个对象进行回收的.
    完!!!!!!

    相关文章

      网友评论

          本文标题:LinkedBlockingQueue (笔记)

          本文链接:https://www.haomeiwen.com/subject/spknjrtx.html