• 深入Java集合学习系列:ArrayBlockingQueue及其实现原理


    http://m.blog.csdn.net/blog/luoyuyou/38265817

    ArrayBlockingQueue是一个基于数组和锁的有容量限制的阻塞队列,事实上它的阻塞能力来自于锁和条件队列。

    我们对关键代码展开:

        public boolean offer(E e, long timeout, TimeUnit unit)
            throws InterruptedException {
    
            checkNotNull(e);
            long nanos = unit.toNanos(timeout);
            final ReentrantLock lock = this.lock;
            lock.lockInterruptibly();
            try {
                while (count == items.length) {
                    if (nanos <= 0)
                        return false;
                    nanos = notFull.awaitNanos(nanos);
                }
                enqueue(e);
                return true;
            } finally {
                lock.unlock();
            }
        }
    这里的过程比较简单也比较熟悉,无非是先获取锁,查看当前个数和容量对比,之后会限时阻塞然后入队列,发送信号并且返回true,最后释放锁。


        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();
            }
        }
    与offer的过程类似,区别只是会从队列中取出节点。

    ArrayBlockingQueue的特点是容量限制,并且锁范围较大,所以大多数情况下可能不是好的选择。



  • 相关阅读:
    My Houdini First Step
    MaxScript随机赋材质
    Groups of Operators
    Select groups in scene
    投篮球
    U3D PlayMovie
    unicornForest
    MaxScript Spinner/progressBar
    MaxScript Button
    MaxScript 扇子打开
  • 原文地址:https://www.cnblogs.com/leeeee/p/7276054.html
Copyright © 2020-2023  润新知