浅析ArrayBlockingQueue 和 LinkedBlockingQueue的阻塞原理

阻塞队列与我们平常接触的普通队列(LinkedList或ArrayList等)的最大不同点,在于阻塞队列支持阻塞添加和阻塞删除方法。

  • 阻塞添加

所谓的阻塞添加是指当阻塞队列元素已满时,队列会阻塞加入元素的线程,直队列元素不满时才重新唤醒线程执行元素加入操作。

  • 阻塞删除

阻塞删除是指在队列元素为空时,删除队列元素的线程将被阻塞,直到队列不为空再执行删除操作(一般都会返回被删除的元素)

阻塞队列 (BlockingQueue)是Java util.concurrent包下重要的数据结构,BlockingQueue提供了线程安全的队列访问方式:当阻塞队列进行插入数据时,如果队列已满,线程将会阻塞等待直到队列非满;从阻塞队列取数据时,如果队列已空,线程将会阻塞等待直到队列非空。并发包下很多高级同步类的实现都是基于BlockingQueue实现的

BlockingQueue 具有 4 组不同的方法用于插入、移除以及对队列中的元素进行检查。如果请求的操作不能得到立即执行的话,每个方法的表现也不同。这些方法如下:

BlockingQueue  的实现有很多,本文只简单介绍下ArrayBlockingQueue 和 LinkedBlockingQueue的阻塞原理。

1.ArrayBlockingQueue

我们利用阻塞队列来实现生产者-消费者模式,先看一个小例子:AB工人生产面包,123同学消费面包:

package com.cjian.threadpool.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;

public class Producer implements Runnable{
    //生产的面包放到这
    private ArrayBlockingQueue<Bread> breadQueue;

    public Producer(ArrayBlockingQueue<Bread> breadQueue) {
        this.breadQueue = breadQueue;
    }

    @Override
    public void run() {
        while(true){
            try {
                //每三秒生产一个面包
                Thread.sleep(3000);
                breadQueue.put(new Bread());
                System.out.println(Thread.currentThread().getName()+"生产了一个面包");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
package com.cjian.threadpool.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;


public class Consumer implements Runnable{
    //从这里消费面包
    private ArrayBlockingQueue<Bread> breadQueue;

    public Consumer(ArrayBlockingQueue<Bread> breadQueue) {
        this.breadQueue = breadQueue;
    }

    @Override
    public void run() {

        while(true){
            try {
                //每一秒消费一个面包
                Thread.sleep(1000);
                breadQueue.take();
                System.out.println(Thread.currentThread().getName()+"消费一个面包");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

测试:

package com.cjian.threadpool.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;

public class Test {

    public static void main(String[] args) {
        ArrayBlockingQueue<Bread> breadQueue = new ArrayBlockingQueue<>(10);

        new Thread(new Producer(breadQueue),"A").start();
        new Thread(new Producer(breadQueue),"B").start();
        new Thread(new Consumer(breadQueue),"1").start();
        new Thread(new Consumer(breadQueue),"2").start();
        new Thread(new Consumer(breadQueue),"3").start();
    }
}

A生产了一个面包
3消费一个面包
B生产了一个面包
1消费一个面包
A生产了一个面包
1消费一个面包
B生产了一个面包
2消费一个面包
B生产了一个面包
A生产了一个面包
3消费一个面包
1消费一个面包

一起来探究下,底层实现:

    //Object数组
    final Object[] items;

    /** items index for next take, poll, peek or remove */
    //下次取元素的下标
    int takeIndex;

    /** items index for next put, offer, or add */
    //下次插入的下标
    int putIndex;

    /** Number of elements in the queue */
    //队列元素大小
    int count;

    /*
     * Concurrency control uses the classic two-condition algorithm
     * found in any textbook.
     */
    /** Main lock guarding all access */
    //只有一把锁,读写共用一把锁
    final ReentrantLock lock;

    /** Condition for waiting takes */
    //获取元素的条件
    private final Condition notEmpty;

    /** Condition for waiting puts */
    //插入元素的条件
    private final Condition notFull;
    
    //指定容量
    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();
    }
    //指定容量,公平性,以及可以对传进来的集合初始化,放入队列中    
    public ArrayBlockingQueue(int capacity, boolean fair,
                              Collection<? extends E> c) {
        this(capacity, fair);

        final ReentrantLock lock = this.lock;
        lock.lock(); // Lock only for visibility, not mutual exclusion
        try {
            int i = 0;
            try {
                for (E e : c) {
                    checkNotNull(e);
                    items[i++] = e;
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                throw new IllegalArgumentException();
            }
            count = i;
            putIndex = (i == capacity) ? 0 : i;
        } finally {
            lock.unlock();
        }
    }

既然用到了阻塞队列,应该都是在使用它的可阻塞特性吧,所以,接下来我们分析put 和take是如何实现的阻塞功能的,其他方法也都很简单,就不分析了

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


private void enqueue(E x) {
        final Object[] items = this.items;
        //直接放入putIndex下标位置
        items[putIndex] = x;
        if (++putIndex == items.length)//如果已经是最后一位了,下次插入需要从0下标开始
            putIndex = 0;
        //自增1
        count++;
        //唤醒取元素的线程
        notEmpty.signal();
    }

 

take

 public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)//count==0,说明队列没有元素,直接阻塞
                notEmpty.await();
            //取出元素
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

private E dequeue() {
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        //取出队首的元素,先进先出
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length)//如果这次取出的元素是数组的最后一位,takeIndex置为0 
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        //有元素被取出,唤醒插入时被阻塞的线程
        notFull.signal();
        return x;
    }

由此可见,阻塞的功能就是通过ReentrantLock 锁的条件(condition)来实现的。

remove

public boolean remove(Object o) {
        if (o == null) return false;
        final Object[] items = this.items;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count > 0) {
                final int putIndex = this.putIndex;
                int i = takeIndex;
                do {
                    if (o.equals(items[i])) {//遍历队列中的元素
                        removeAt(i);
                        return true;
                    }
                    if (++i == items.length)
                        i = 0;
                } while (i != putIndex);
            }
            return false;
        } finally {
            lock.unlock();
        }
    }

总结下ArrayBlockingQueue:

数据结构:静态数组,容量固定

锁:ReentrantLock,存取是同一把锁

阻塞:notEmpty 出队:当count==0 时,阻塞当前线程; notFull 入队:当count大小等于数据大小时,阻塞当前线程

入队:从队首开始添加,并记录putIndex(到队位时置为0),并唤醒notEmpty

出队:从队首开始取,记录takeIndex (到队位时置为0),唤醒notFull

先进先出,读写互相排斥

2.LinkedBlockingQueue

    private final int capacity; // 队列容量,如果构造时未指定则为Integer.MAX_VALUE

	//使用AtomicInteger来统计队列中元素数量
    private final AtomicInteger count = new AtomicInteger(0);

    /**
     * Head of linked list.
     * Invariant: head.item == null
     */
    private transient Node<E> head; // 队列的头元素 值为null 

    /**
     * Tail of linked list.
     * Invariant: last.next == null
     */
    private transient Node<E> last; // 队列的尾元素 它的下一个节点为null

    /** Lock held by take, poll, etc */
    private final ReentrantLock takeLock = new ReentrantLock(); // 出队锁

    /** Wait queue for waiting takes */
    private final Condition notEmpty = takeLock.newCondition(); // 取出线程condition

    /** Lock held by put, offer, etc */
    private final ReentrantLock putLock = new ReentrantLock(); // 入队锁

    /** Wait queue for waiting puts */
    private final Condition notFull = putLock.newCondition(); // 添加线程condition

构造函数: 

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

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

 put

 public void put(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException();//先检查添加值是否为null
        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();
    }


private void enqueue(Node<E> node) {
        last = last.next = node; //将新的节点添加到队尾,并变成新的尾节点
    }

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

private E dequeue() {
        Node<E> h = head; //队列的头结点是值为null的节点
        Node<E> first = h.next; //返回头节点之后的第一个节点
        h.next = h; // help GC 
        //因为创建节点时创建了一个新的对象,所以需要GC,即需要将头节点的后继节点指向自身,帮助GC
        head = first;//将新的头节点置为将要删除的第一个节点
        E x = first.item; //将节点的值赋给x
        first.item = null;//将节点值置为null,变为新的头节点
        return x;//返回取出的值
    }



  private void signalNotFull() {
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
            notFull.signal();
        } finally {
            putLock.unlock();
        }
    }

 

 

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

void fullyLock() {
        putLock.lock();
        takeLock.lock();
    }

链表Node   可以指定容量,默认Integer.MAX_VALUE,内部Node存储元素

锁分离: 存取互不排斥,操作的是不同的node对象:  takeLock      取Node节点保证前驱后继不会乱

                                                                                      putLock        存node节点保证前驱后继不会乱

阻塞     同ArrayBlockingQueue

入队:队尾入队  记录last节点  指向刚入队的

出队:队首出队  记录head节点  然后head往后移

删除元素的时候两个锁一起加

先进先出    

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值