ArrayBlockingQueue源码阅读与理解

ArrayBlockingQueue源码阅读与理解

简介:FIFO队列,运用重入锁配合Condition控制多线程进出,算法:运用一个Object数组,插入顺序0->length->0满了则等待,0->length->0逐个取空了想取也等待。

几个变量:

    //数据存储
    final Object[] items;
    //取数据指针
    int takeIndex;
    //放数据指针
    int putIndex;
    //个数
    int count;

    //重入锁
    final ReentrantLock lock;
    //队列空的时候,重入的情况下,取数据就会进入notEmpty等待队列
    private final Condition notEmpty;
    //队列满的时候,重入的情况下,插入数据就会进入notFull等待队列
    private final Condition notFull;
    //迭代器对象
    transient Itrs itrs = null;

几个方法:

//插入队尾
public boolean add(E e) {
        return super.add(e);
    }
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();
        }
    }
private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        //赋值
        items[putIndex] = x;
        //队列满了index返回0
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        //唤醒一个等待取值队列
        notEmpty.signal();
    }
//插入队尾
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();
        }
    }
//弹出
public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
    }
//出队
private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        //置空
        items[takeIndex] = null;
        //满了则index又返回0
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        //唤醒一个等待插入队列
        notFull.signal();
        return x;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值