JAVA队列介绍(Queue)——ArrayBlockingQueue和LinkedBlockingQueue

ArrayBlockingQueue

ArrayBlockingQueue是采用数组实现的有界阻塞线程安全队列。如果向已满的队列继续塞入元素,将导致当前的线程阻塞。如果向空队列获取元素,那么将导致当前线程阻塞。

java实现原理

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

    private static final long serialVersionUID = -817911632652898426L;

    // 队列中的子项
    final Object[] items;

    // 取出子项的索引
    int takeIndex;

    // 插入数据的子项
    int putIndex;

    // 队列中数据的总数
    int count;

    // 锁对象
    final ReentrantLock lock;
    
    // 非空条件
    private final Condition notEmpty;

    // 非满条件
    private final Condition notFull;
    
    transient Itrs itrs = null;
}

构造函数

    public ArrayBlockingQueue(int capacity) {
        // 指定了数组的长度,使用非公平锁作为锁工具
        this(capacity, false);
    }

    public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        // 获得锁的条件,赋值给非空
        notEmpty = lock.newCondition();
        // 获得锁的条件、赋值给非满
        notFull =  lock.newCondition();
    }

上面是ArrayBlockingQueue内部维护的属性和其提供的构造函数,可以中间有几个属性是其关键:
items:是queue具体维护元素的地方,其是一个在初始化队列的之后就要被指定长度的数组。
lock:通过锁来保证队列的操作都是线程安全的。
count:负责记录整个队列中元素的数量
xxxIndex: 两个索引的数据,负责记录当前添加数据的索引和当前取出数据的索引。(关于两个索引是如何运作的,可以在后续看数据添加和取出的代码。上面有介绍其运作方式)

构造函数:在其构造函数中可以发现其默认使用了非公平锁的方式,初始化锁工具,有关于非公平锁的内容,可以查询其他关于公平以及非公平锁的内容,或者查看我之前的文章中也有介绍。

基础操作

新增

ArrayBlockingQueue 提供了add、offer、put方式添加元素:

add

    public boolean add(E e) {
        return super.add(e);
    }


    public boolean add(E e) {
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
    }

实际上从源码上可以看出来,add底层实际上就是使用了offer的方法进行元素的添加。

offer

    public boolean offer(E e) {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length)
                return false;
            else {
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }

put

    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }

所以其添加元素的方法主要是offer以及put两种方式。
在代码中可以看到,两者在新增数据的时候都使用了加锁的方式,来保证线程的安全。而不同之处,在put方法中,当检测到元素的总数等于数据长度(队列已满)。此时添加元素的动作将会阻塞。

enqueue
    private void enqueue(E x) {
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        notEmpty.signal();
    }

enqueue是队列中最终进行数据添加的逻辑。从中可以看到其除了修改了count的内容,还使用了之前我们讲到的两个索引值。
在添加数据的时候会将新的数据添加到put索引后移一位的位置中,假如此时索引已经移动至队尾的时候索引会被重置到0的位置。

takeIndex:0,putIndex:2
data
data
null
null

此时插入两个数据后会变为

takeIndex:0,putIndex:4
data
data
data
data

此时取出两个数据然后插入一个数据,putIndex因为达到数组的上限会被重置为0从头开始,所以会变为

takeIndex:2,putIndex:1
data
null
data
data
取出/删除数据

我们使用poll、peek以及take取出数据。

peek

    public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return itemAt(takeIndex); // null when queue is empty
        } finally {
            lock.unlock();
        }
    }
    
    final E itemAt(int i) {
        return (E) items[i];
    }
    

peek是一种只进行查看,而不会移除元素的方式,使用此方法返回的是takeIndex位置的元素。

poll

    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
    }

take

    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

poll和take,使用了dequeue的方式去获得元素,此操作实际会进行元素的移除。而poll和take的区别是,在take方法中,当队列中元素而空的时候将会阻塞,直到存在数据,而poll方法会直接返回null。

dequeue

    private E dequeue() {
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        notFull.signal();
        return x;
    }

dequeue和enqueue对应,其会获得takeIndex处的元素,然后将数组中此位置的元素设置为null。然后将takeIndex

额外部分newCondition

下面内容主要涉及锁的一些使用,本不属于队列里面的,但是为了避免理解困难,所以在这里简单介绍下。

在初始化ArrayBlockingQueue的时候可以看到其使用newCondition初始化了两个条件Condition。

    // 获得锁的条件,赋值给非空
    notEmpty = lock.newCondition();
    // 获得锁的条件、赋值给非满
    notFull =  lock.newCondition();

这里就涉及了newCondition的使用。Condition的作用是为了解决一种场景。当我们有很多线程被阻塞的时候,我们只想唤醒每一种或者每一类线程的时候,Condition提供给我们精准找出这些线程的方式。

比如当我们向一个队列插入\读取元素的时候,当完成插入数据之后我们需要唤醒读取元素的线程,当我们完成读取元素的时候,需要唤醒插入元素的线程。假如我们使用了object的环境操作的时候,我们不知道具体唤醒的是哪一种线程,可能导致读完完数据后再次唤醒读取数据,或者插入数据的时候再次唤醒插入数据。

而使用通过Condition,我们在阻塞的时候就已经完成了类别的标记,在环境线程的时候,就能明确的指定唤醒读线程。

.Condition中的await()方法相当于Object的wait()方法,Condition中的signal()方法相当于Object的notify()方法。

关于ArrayBlockingQueue

从源码中可以看出ArrayBlockingQueue内部是采用数组进行数据存储的(属性items),为了保证线程安全,采用的是ReentrantLock lock,为了保证可阻塞式的插入删除数据利用的是Condition,当获取数据的消费者线程被阻塞时会将该线程放置到notEmpty等待队列中,当插入数据的生产者线程被阻塞时,会将该线程放置到notFull等待队列中。而notEmpty和notFull等中要属性在构造方法中进行创建:


LinkedBlockingQueue

LinkedBlockingQueue 链表实现的有界阻塞队列, 此队列的默认和最大长度为
Integer.MAX_VALUE。此队列按照先进先出的原则对元素进行排序

java实现原理

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();

    /**
     * 链表的头部
     */
    transient Node<E> head;

    /**
     * 链表尾部
     */
    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();   
        
}

基础操作

新增

LinkedBlockingQueue提供了put和offer两种方式进行元素的添加

    public boolean offer(E e) {
        if (e == null) throw new NullPointerException();
        final AtomicInteger count = this.count;
        // 超过容量则返回false
        if (count.get() == capacity)
            return false;
        int c = -1;
        Node<E> node = new Node<E>(e);
        // 获得新增数据的锁
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
            // 数据未超限的时候则插入数据
            if (count.get() < capacity) {
                enqueue(node);
                // 自增count的值,并返回之前的值
                c = count.getAndIncrement();
                // 队列中的元素未满的时候则环境插入数据的线程
                if (c + 1 < capacity)
                    notFull.signal();
            }
        } finally {
            putLock.unlock();
        }
        // c == 0 表示之前的值为0为空队列,现在队列已经存在元素了。则唤醒取数据的线程
        if (c == 0)
            signalNotEmpty();
        return c >= 0;
    }
    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.await();
            }
            enqueue(node);
            c = count.getAndIncrement();
            // 队列中的元素未满的时候则环境插入数据的线程
            if (c + 1 < capacity)
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
    }

和之前的队列一样,put和offer分别是其阻塞和非阻塞的插入元素的方法。在插入方法之间使用Condition来唤醒不同的线程:插入元素后发现队列未满则唤醒其他插入数据的线程,插入元素后发现之前队列为空则唤醒其他取数据的线程。

enqueue

上面的put和offer其使用enqueue方法进行最终的数据插入操作:

    private void enqueue(Node<E> node) {
        last = last.next = node;
    }

其逻辑就非常简单,主要是向尾部添加元素,并将新的元素指向last属性。从这里看到。不同于LinkedList实现的头尾添加元素,LinkedBlockingQueue的数据保存只能从尾部进行添加。

取出/删除数据

LinkedBlockingQueue提供了peek、poll、take三个方法获得元素。

    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)
                return null;
            else
                return first.item;
        } finally {
            takeLock.unlock();
        }
    }

peek和另外两个方法不同,其只是获得元素并不会移除相关数据。所以其只是将头部元素返回。此处需要注意正常我们理解应该返回的是head.item的内容但实际上返回的是Node<E> first = head.next。因为此时head.item并不是真正的第一个元素,而是上一个被取出的元素,至于原因可以在poll、take方法中找到原因。

    public E poll() {
        final AtomicInteger count = this.count;
        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;
    }
    
    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;
    }

poll和take两者除了在阻塞的逻辑之外,具体逻辑并没有差别。主要流程:

  1. 在流程之前执行takeLock的加锁操作
  2. 在不存在数据的时候take会进行阻塞、poll则直接返回false
  3. 在发现依然存在值得请款下则唤醒其他取值的线程
  4. 在发现之前数据为满时唤醒其他插入数据的线程(因为此时已经取出了一个)

dequeue

    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;
    }

dequeue是其最终取出元素的方法。在代码中我们可以发现。我们实际取出的值为head.next。并且在取出后其item会被设置为null。所以此时head元素指的是上一个被take掉的node。而此时存在头部的数据应该是head.next指向的node。

关于LinkedBlockingQueue

可以看出与ArrayBlockingQueue主要的区别是,LinkedBlockingQueue在插入数据和删除数据时分别是由两个不同的lock(takeLock和putLock)来控制线程安全的,因此,也由这两个lock生成了两个对应的condition(notEmpty和notFull)来实现可阻塞的插入和删除数据。并且,采用了链表的数据结构来实现队列。


个人水平有限,上面的内容可能存在没有描述清楚或者错误的地方,假如开发同学发现了,请及时告知,我会第一时间修改相关内容。假如我的这篇内容对你有任何帮助的话,麻烦给我点一个赞。你的点赞就是我前进的动力。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

大·风

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

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

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

打赏作者

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

抵扣说明:

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

余额充值