阻塞队列之LinkedBlockingQueue

  作为一个队列,这个队列还是蛮特殊的,今天第一次遇见,好像很有用,我决定晚上回家之后研究研究。

一:概述

  LinkedBlockingQueue内部由单链表实现,只能从head取元素,从tail添加元素。实现了先进先出等特性,是作为生产者消费者的首选。

  添加元素和获取元素都有独立的锁,也就是说LinkedBlockingQueue是读写分离的,读写操作可以并行执行。

  LinkedBlockingQueue采用可重入锁(ReentrantLock)来保证在并发情况下的线程安全。

  其中主要用到put和take方法,put方法在队列满的时候会阻塞直到有队列成员被消费,take方法在队列空的时候会阻塞,直到有队列成员被放进来。

二:构造器

  LinkedBlockingQueue一共有三个构造器,分别是无参构造器、可以指定容量的构造器、可以穿入一个容器的构造器。

  如果在创建实例的时候调用的是无参构造器,LinkedBlockingQueue的默认容量是Integer.MAX_VALUE,这样做很可能会导致队列还没有满,但是内存却已经满了的情况(内存溢出)。

1 public LinkedBlockingQueue();   //设置容量为Integer.MAX
2 
3 public LinkedBlockingQueue(int capacity);  //设置指定容量
4 
5 public LinkedBlockingQueue(Collection<? extends E> c);  //穿入一个容器,如果调用该构造器,容量默认也是Integer.MAX_VALUE

  

三:常用操作

取数据

take():首选。当队列为空时阻塞

poll():弹出队顶元素,队列为空时,返回空

peek():和poll烈性,返回队队顶元素,但顶元素不弹出。队列为空时返回null

remove(Object o):移除某个元素,队列为空时抛出异常。成功移除返回true

添加数据

put():首选。队满是阻塞

offer():队满时返回false

判断队列是否为空

size()方法会遍历整个队列,时间复杂度为O(n),所以最好选用isEmtpy

四:详细说明

LinkedBlockingQueue的添加方法

put(e)

  该方法没有返回值,当队列已满时,会阻塞当前线程

public void put(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException();//先检查添加值是否为null
        // 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; //使用putLock来保证线程安全
        final AtomicInteger count = this.count;
        putLock.lockInterruptibly();
        try {
 
            while (count.get() == capacity) {//当队列已满,添加线程阻塞
                notFull.await();
            }
            enqueue(node); // 调用enqueue方法添加到队尾
            c = count.getAndIncrement(); //调用AtomicInteger的getAndIncrement()是数量加1
            if (c + 1 < capacity)//添加成功后判断是否可以继续添加,队列未满
                notFull.signal(); //唤醒添加线程
        } finally {
            putLock.unlock();
        }
        if (c == 0) // 添加后如果队列中只有一个元素,唤醒一个取出线程,使用取出锁
            signalNotEmpty();
    }

  

offer(e,timeout,unit)

  该方法返回true或false,当队列已满时,会阻塞给定时间,添加操作成功返回true,否则返回false

public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException {
 
        if (e == null) throw new NullPointerException();
        long nanos = unit.toNanos(timeout);
        int c = -1;
        final ReentrantLock putLock = this.putLock; //使用putLock
        final AtomicInteger count = this.count;
        putLock.lockInterruptibly();
        try {
            while (count.get() == capacity) { //当队列已满阻塞给定时间
                if (nanos <= 0) //当时间消耗完全,操作未成功 返回false
                    return false; 
                nanos = notFull.awaitNanos(nanos);
            }
            enqueue(new Node<E>(e)); // 调用enqueue方法添加一个新的节点
            c = count.getAndIncrement(); //同样调用AtomicInteger的方法
            if (c + 1 < capacity)
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
        return true; // 操作成功返回true
    }

  

offer(e)

  该方法返回true或false,不会阻塞,直接返回

public boolean offer(E e) {
        if (e == null) throw new NullPointerException();
        final AtomicInteger count = this.count;
        if (count.get() == capacity)
            return false; //当队列已满,直接返回false
        int c = -1;
        Node<E> node = new Node(e); // 先创建新的节点
        final ReentrantLock putLock = this.putLock;//使用putLock
        putLock.lock();
        try {
            if (count.get() < capacity) { // 加锁后再次判断队列是否已满
                enqueue(node); //调用enqueue方法将节点添加到队尾
                c = count.getAndIncrement();
                if (c + 1 < capacity)
                    notFull.signal();
            }
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
        return c >= 0; // 比较c的大小,判断是否成功,当c大于-1时则添加操作成功
    }

  

LinkedBlockingQueue的取出方法

take()

public E take() throws InterruptedException {
        E x;
        int c = -1;
        final AtomicInteger count = this.count;
        final ReentrantLock takeLock = this.takeLock;//使用takeLock保证线程安全
        takeLock.lockInterruptibly();
        try {
            while (count.get() == 0) {//当队列为空,取出线程阻塞
                notEmpty.await();
            }
            x = dequeue(); //掉用dequeue方法从队头取出元素
            c = count.getAndDecrement(); //调用AtomicInteger的getAndDecrement()将count值减1
            if (c > 1)//判断如果当前队列之前元素的数量大于1,唤醒取出线程
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)//之前队列元素数量为容量值,取出一个,只能唤醒一个添加线程
            signalNotFull();
        return x;
    }

  

poll(timeout,unit)

  该方法取出元素时,如果队列为空,则阻塞给定的时间

public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        E x = null;
        int c = -1;
        long nanos = unit.toNanos(timeout);
        final AtomicInteger count = this.count;
        final ReentrantLock takeLock = this.takeLock;//使用takeLock保证线程安全        
        takeLock.lockInterruptibly();
        try {
            while (count.get() == 0) {//当队列为空则阻塞给定时间
                if (nanos <= 0)//时间消耗完全后,如果操作未成功则返回null
                    return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
            x = dequeue();//调用dequeue方法返回节点值
            c = count.getAndDecrement();//将count值减1
            if (c > 1)
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)
            signalNotFull();
        return x;
    }

  

poll()

  该方法取出元素时,如果队列为空,则直接返回null

public E poll() {
        final AtomicInteger count = this.count;
        if (count.get() == 0)// 如果队列为空,直接返回null
            return null;
        E x = null;
        int c = -1;
        final ReentrantLock takeLock = this.takeLock;//使用takeLock保证线程安全
        takeLock.lock();
        try {
            if (count.get() > 0) {
                x = dequeue();//调用dequeue方法取出队头节点元素的值
                c = count.getAndDecrement();//count减1
                if (c > 1)//如果取出元素不是唯一的,唤醒取出线程
                    notEmpty.signal();
            }
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)//如果从已满队列取出的,则唤醒一个添加线程
            signalNotFull();
        return x;
    }

  

peek()

  该方法只返回队头元素的值,并不能将节点从队列中删除

public E peek() {
        if (count.get() == 0)
            return null;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();
        try {
            Node<E> first = head.next;
            if (first == null)//如果队列为空,则直接返回null
                return null;
            else
                return first.item;
        } finally {
            takeLock.unlock();
        }
    }

  

remove(o)

  从队列中删除指定元素值的节点

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);//调用unlink删除此节点
                    return true;//操作成功返回true
                }
            }
            return false;
        } finally {
            fullyUnlock();
        }
    }

  

获取队列当前大小及剩余容量

size()

 public int size() {
        return count.get();
    }

  

remainingCapacity()

public int remainingCapacity() {
        return capacity - count.get();
    }

  

这两个方法都没有使用锁来保证线程安全,是因为count自身为AtomicInteger对象,保证了操作的原子性

原文地址:https://www.cnblogs.com/juncaoit/p/12570918.html