阻塞队列的小笔记

简介

阻塞队列在应用广泛,例如线程池。其原理就是用了锁机制。

API规范

API12容量到达限制阻塞(阻塞队列使用核心)
插入add()(到达容量阻塞)offer() (返回添加成功与否)put()
移除remove() (返回移除成功与否)poll() (返回移除的元素)take()

原理

这里以ArrayBlockingQueue为例

add和remove

add

public boolean add(E e) {
	//调用了父类的add
    return super.add(e);
}
public boolean add(E e) {
	//很简单,尝试插入,成功为true,否则抛出异常
    if (offer(e))
        return true;
    else
        throw new IllegalStateException("Queue full");
}

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);
                    //成功移除返回true
                    return true;
                }
                if (++i == items.length)
                    i = 0;
            } while (i != putIndex);
        }
        //移除失败返回false
        return false;
    } finally {
        lock.unlock();
    }
}

offer和poll

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

poll

public E poll() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
    	//这里调用了dequeue()
        return (count == 0) ? null : 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;
    count--;
    if (itrs != null)
        itrs.elementDequeued();
    //这里是给put和take用的
    notFull.signal();
    //将前面获取的节点返回
    return x;
}

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

take

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0)
        	//如果队列为空就阻塞
            notEmpty.await();
        return dequeue();
    } finally {
        lock.unlock();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值