基于ArrayBlockingQueue理解AQS部分源码

阻塞队列

  • 阻塞队列ArrayBlockingQueue是JUC包提供用于解决生产者-消费者问题最有用的类。
  • 当阻塞队列满时,往队列里添加元素的操作将会阻塞。当队列是空时,从队列中取元素的操作将被阻塞;
  • 试图从空的阻塞队列中获取元素的线程将会被阻塞,直到其他的线程往空的队列插入新的元素。
  • 试图往己满的阻塞队列中添加新元素的线程同样也会被阻塞,直到其他的线程从列中移除一个或者多个元素,或者完全清空队列后使队列重新变得空闲起来并后续新增一些元素
  • 阻塞队列图如下:
    在这里插入图片描述
    在这里插入图片描述

队列类型

  • 无界队列: 容量无限
    向无限队列添加元素的所有操作都将永远不会阻塞,因此它可以增长到非常大的容量。
    使用无限 BlockingQueue 设计生产者 - 消费者模型时最重要的是 消费者应该能够像生产者向队列添加消息一样快地消费消息 。否则,内存可能会填满,然后就会得到一个 OutOfMemory 异常。
  • 优先队列: 容量有限

阻塞队列的好处

  • 在多线程领域,阻塞就是在某些情况下挂起线程,一旦条件满足,被挂起的线程又被会唤醒;
  • 好处是线程的唤醒和阻塞不需要我们手动控制。
  • 线程的阻塞唤醒由阻塞队列包办了。

阻塞队列分类

  1. ArrayBlockingQueue:有数组结构组成的有界阻塞队列。初始容量为5;
    在这里插入图片描述
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>();
  1. LinkedBlockingQueue:由链表组成的有界队列(最大为Integer.MAX_VALUE)

  2. SynchronousQueue:不存储元素的阻塞队列,也即单个元素的队列-生产一个、消费一个;

  3. PriorityBlockingQueue:支持优先级排序的无界阻塞队列5)DelayQueue:使用优先级队列实现的延迟无界阻塞队列

阻塞队列API

在这里插入图片描述

  • 抛出异常
    1)当阻塞队列满时、再往队列里add插入元素会抛出IllegalStateException:Queue full
    2)当阻塞队列空时,再往队列里remove移除元素会抛NoSuchElementException

  • 返回布尔
    插入方法,成功 ture 失败 false
    移除方法,成功返回出队列的元素,队列里面没有就返回null

  • 一直阻塞
    当阻塞队列满时,生产者线程继续往队列里put元素,队列会一直阻塞生产线程直到put数据成功或者响应中断退出。
    当阻塞队列空时,消费者线程试图从队列里take元素,队列会一直阻塞消费者线程直到队列可用。

  • 超时退出
    当阻塞队列满时,队列会阻塞生产者线程一定时间,超过后限时后生产者线程会退出

生产者消费者

import java.util.concurrent.SynchronousQueue;

public class SynchronousQueueTest {
    public SynchronousQueue<Object> queue=new SynchronousQueue<>();
    public void add(Object val) throws InterruptedException {
        queue.put(val);
    }
    public Object get() throws InterruptedException {
        return queue.take();
    }

    public static void main(String[] args) {
        SynchronousQueueTest demo=new SynchronousQueueTest();
        new Thread(()->{
            for (int i=0; i<10;i++){
                try {
                    demo.add(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AAA").start();
        new Thread(()->{
            for (int i=0; i<10;i++){
                try {
                    System.out.println("获得元素"+demo.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BBB").start();
    }
}

ArrayBlockingQueue源码

先分析生产,再分析消费;
建议先看一下这篇博文:基于ReentrantLock的AQS源码理解

1. new ArrayBlockingQueue()

  public ArrayBlockingQueue(int capacity) {
        this(capacity, false);
    }
 
  public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
            //创建一个容器,容量为capacity大小
        this.items = new Object[capacity];
        //创建一把可重入锁,且是非公平锁;
        lock = new ReentrantLock(fair);
        //创建一个非空条件Condition,
        notEmpty = lock.newCondition();
            //创建一个非满条件Condition,
        notFull =  lock.newCondition();
    }

notEmpty 、notFull 后面会用到;

2. put(Object obj)

    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        //获取阻塞队列里的锁
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
        //判断是否容量是否满了,满则使用notFull将当前线程阻塞;
            while (count == items.length)
                notFull.await();
            //将数据放入容器中;
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }

2.1 enqueue(e)
 private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        //获取容器,将生产的对象放入容器中;
        items[putIndex] = x;
        //putIndex,插入数组的索引号
        //这里表示满了,putIndex重置,从0位置开始插入数据;
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        //唤醒等待队列中消费者;
        notEmpty.signal();
    }

2.1.1 notEmpty.signal()
     public final void signal() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
                //获取头指针
            Node first = firstWaiter;
            if (first != null)
            //不为空则将等待队列的消费者线程转义到CLH同步队列里。
                doSignal(first);
        }
2.1.2 doSignal(Node first)
       private void doSignal(Node first) {
            do {
            //这里只想下一个结点,判断是否为空,为空说明等待队列空了。
                if ( (firstWaiter = first.nextWaiter) == null)
                    lastWaiter = null;
                first.nextWaiter = null;
            //transferForSignal将等待队列上的结点送到CLH队列
            } while (!transferForSignal(first) &&
                     (first = firstWaiter) != null);
        }
2.1.3 transferForSignal(Node node)
    final boolean transferForSignal(Node node) {
        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
            return false;
            //enq入队,AQS核心方法之一;
        Node p = enq(node);
        int ws = p.waitStatus;
        //获取这些结点的等待状态,如果Condition状态,则改为Signal状态;
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
            //接着唤醒线程;
            LockSupport.unpark(node.thread);
        return true;
    }

2.1.4 enq(node)
    private Node enq(final Node node) {
        for (;;) {
        //获取CLH尾指针,如果为空,创建傀儡结点,再自旋一次,再将结点插入CLH的尾部;
            Node t = tail;
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
            //设置当前结点的前向指针为尾指针指向的尾结点。
                node.prev = t;
                //通过CAS,设置新的尾指针Tail,
                //因为可能会有多个线程入队;
                if (compareAndSetTail(t, node)) {
                //当前结点的前一个结点的后向指针指向当前结点。
                    t.next = node;
                    return t;
                }
            }
        }
    }

这样,生产完后,就会将消费者线程全部唤醒,进入CLH里面争抢锁。

2.2 notFull.await()

表示容器已经满,当前生产者线程需要等一下,即阻塞一段时间。等容器的数据被消费了再继续生产;
在这里插入图片描述
await的实现是在AQS里面实现的,AQS里面定义了ConditionObject的内部类,存在一个单向的条件等待队列
数据结构如下:

   public class ConditionObject implements Condition, java.io.Serializable {
        private static final long serialVersionUID = 1173984872572414699L;
       //等待队列的头指针
        private transient Node firstWaiter;
        //等待队列的尾指针
        private transient Node lastWaiter;

   public final void await() throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
                //加入等待队列而不是CLH同步队列
            Node node = addConditionWaiter();
            //释放锁
            int savedState = fullyRelease(node);
            int interruptMode = 0;
            //判断是否在等待队列里面,如果在,则阻塞;
            while (!isOnSyncQueue(node)) {
                LockSupport.park(this);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
        }
2.2.1 addConditionWaiter()

        private Node addConditionWaiter() {
            //获得尾指针所指向的结点;
            Node t = lastWaiter;
          //如果尾指针不为康,但是等待状态不是条件等待状态,则将该节点从等待队列中移除,并重新指向新的尾结点;
            if (t != null && t.waitStatus != Node.CONDITION) {
                unlinkCancelledWaiters();
                t = lastWaiter;
            }
            //创建一个等待队列的结点,封装当前线程,以及等待状态
            Node node = new Node(Thread.currentThread(), Node.CONDITION);

            if (t == null)
                firstWaiter = node;
                            //如果尾结点为空,则等待队列为空,则头指针指向当前结点。
            else
            //如果不为空,则插入等待队列的尾部;
                t.nextWaiter = node;
//重新设置一下尾指针,指向新的尾结点。
            lastWaiter = node;
            return node;
        }
2.2.2 fullyRelease(node)

释放锁,将state设置为0,使阻塞队列里的可冲入锁状态变为0,让消费者线程去获取这把锁;

    final int fullyRelease(Node node) {
        boolean failed = true;
        try {
        //获取state;
            int savedState = getState();
            //释放锁;
            if (release(savedState)) {
                failed = false;
                return savedState;
            } else {
                throw new IllegalMonitorStateException();
            }
        } finally {
            if (failed)
                node.waitStatus = Node.CANCELLED;
        }
    }
    
   public final boolean release(int arg) {
   //tryRelease复位state
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
            //这里是唤醒CLH队列的傀儡结点的下一个结点。。
                unparkSuccessor(h);
            return true;
        }
        return false;
    }
    
	protected final boolean tryRelease(int releases) {
	//获取state,并操作变为0;
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
               //将生产者线程设置为null,让消费者去争抢这把锁; 
                setExclusiveOwnerThread(null);
            }
            //设置state状态为0;
            setState(c);
            return free;
        }
2.3 isOnSyncQueue(Node node)

判断生产者是否在CLH同步队列里。因为同时间,一旦消费者消费完,阻塞队列为空,则需要唤醒生产者线程,会将条件队列的消费者全部转移到CLH里。

  final boolean isOnSyncQueue(Node node) {
        if (node.waitStatus == Node.CONDITION || node.prev == null)
            return false;
  //如果下一个结点不为空,则说明在CLH里。
  //刚刚我们常见的结点里,后向指针是为空的。
        if (node.next != null) // If has successor, it must be on queue
            return true;

        return findNodeFromTail(node);
    }

如果该节点不在CLH队列,返回false;
条件成立,使用LockSupport的park方法阻塞生产者线程;

在这里插入图片描述

3. take()

消费者获取 容器里的数据;


    public E take() throws InterruptedException {
    //抢这把锁;
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
        //如果容器里没有东西,则阻塞当前消费者线程;
            while (count == 0)
                notEmpty.await();
   //数据出队;
            return dequeue();
        } finally {
            lock.unlock();
        }
    }
3.1 dequeue()
    private E dequeue() {
        final Object[] items = this.items;
        E x = (E) items[takeIndex];
        //获取数据,takeIndex表示数据在容器中的哪个位置。
        items[takeIndex] = null;
        //拿到之后,将这个数据置空,表示删除;
        if (++takeIndex == items.length)
            takeIndex = 0;
            //表示容量值-1;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        //消费了之后,唤醒生产者;
        //将所有生产者移动到CLH队列里,signal()方法过程和2.1一样。
        notFull.signal();
        return x;
    }

3.2 await()

阻塞队列容器里没有数据,将消费者线程封装为等待队列的结点,存入等待队列;
过程如3.2一样。

 public final void await() throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();
            int savedState = fullyRelease(node);
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {
                LockSupport.park(this);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
        }

通过源码解读,大概懂了为什么BlockingQueue可以用于生产者消费者模型中。
BlockingQueue中维护了一把可重入锁,生产者生产,消费者消费都需要去竞争这一把锁;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值