嘟哝之JDK -- ArrayBlockingQueue

本文深入介绍了ArrayBlockingQueue的实现原理,包括其作为FIFO有界阻塞队列的基础结构、线程公平策略、非阻塞及阻塞的入队与出队操作、锁机制以及迭代器的使用。

简介

ArrayBlockingQueue是一个FIFO的有界阻塞队列。array数组Object[] items存储,采用生产者-消费者模式入队和出队,支持线程公平策略。

Queue接口

抛异常1方法不抛异常接口
addoffer
removepoll
elementpeek

入队

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

offer方法是个非阻塞的方法,一旦判断出数组满则立即返回false。add方法调用了offer方法,如果offer方法返回false,则抛出异常。

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

notFull用于保存当前请求入队的线程到等待链表中;notEmpty用于将阻塞的线程唤醒。

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

出队

非阻塞:

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

阻塞:

public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0) {
            if (nanos <= 0)
                return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
        return dequeue();
    } finally {
        lock.unlock();
    }
}
public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0)
            notEmpty.await();
            return 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;
    if (++takeIndex == items.length)
        takeIndex = 0;
    count--;
    if (itrs != null)
        itrs.elementDequeued();
    notFull.signal();
    return x;
}

出队和入队共享一个ReentrantLock.

迭代器

IteratorListIterator,前者主要用于遍历和删除,后者还可以用于插入元素。


  1. add会抛出IllegalStateException,remove和element会抛出NoSuchElementException.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值