zoukankan      html  css  js  c++  java
  • 深入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的特点是容量限制,并且锁范围较大,所以大多数情况下可能不是好的选择。



  • 相关阅读:
    Charles抓包使用教程
    学习规划
    log重复数据
    CNN实现推特文本分类
    conda env
    matplotlib画基础表
    决策树算法
    sklearn实现决策树
    分词与文本预处理工具
    matplotlib作图学习(1)
  • 原文地址:https://www.cnblogs.com/leeeee/p/7276054.html
Copyright © 2011-2022 走看看