美文网首页
阻塞队列BlockingQueue

阻塞队列BlockingQueue

作者: WLHere | 来源:发表于2020-09-12 19:07 被阅读0次

    BlockingQueue说明

    1. 提供对存取的阻塞功能,在存取时适时等待
    2. 存:如果没有可用空间,则等待直到有空间存储
    3. 取:如果队列为空,则等待直到队列有值

    BlockingQueue方法和结果

    Throws Exception 返回特殊值 阻塞 超时
    Insert add(o) offer(o) put(o) offer(o, timeout,timeunit)
    Remove remove(0) poll() take() poll(timeout, timeunit)
    Examine element() peek() not applicable not applicable

    BlockingQueue分类

    1. ArrayBlockingQueue
    1. 基于数组实现的有界队列。使用双指针(takeIndex、putIndex)来分指向取和添加元素的位置
    2. 锁、等待、唤醒通过ReentrantLock实现,分别用notEmpty和notFull的condition来实现等待和唤醒
    3. 在创建的时候即申请指定大小内存
    4. 在容量小的情况下,使用ArrayBlockingQueue避免动态创建节点(和LinkedBlockingQueue对比)
    5. 默认非公平锁,可以设置公平锁
    1. LinkedBlockingQueue
    1. 基于单向链表实现的可选有界队列。有头尾指针:head和last
    2. 锁、等待、唤醒通过ReentrantLock实现。有两个锁takeLock和putLock。takeLock输出notEmpty Condition,putLock输出notFull Condition
    3. 随着添加元素申请内存;如果不指定大小则为Interger.MAX;
    4. 在容量大的时候使用LinkedBlockingQueue避免在刚开始就申请大内存(和ArrayBlockingQueue对比)
    5. 默认非公平锁,不可改变
    1. PriorityBlockingQueue
    1. 基于数组实现的无界队列,数组是平衡2叉堆方式的方式。顶点元素小于子节点元素,最小的元素在0位置。
    2. 可以设置comparator来排序,如果comparator为空则使用对象的默认排序来实现。
    3. 默认非公平锁,不可改变
    1. DelayQueue
    1. 基于PriorityBlockingQueue实现的无界等待队列
    2. 元素必须实现Delayed接口,返回需要的延迟时间
    3. 取元素时如果 delay大于0,则等待delay时间。等待之后再次进行取操作。
    4. 等待机制:使用ReentrantLock.Condition.awaitNanos(long nanosTimeout)
    5. 默认非公平锁,不可改变
    1. SynchronousQueue
    1. 空队列,存取必须是成对的操作,否则进入等待
    2. 默认非公平锁,可以设置公平锁

    相关文章

      网友评论

          本文标题:阻塞队列BlockingQueue

          本文链接:https://www.haomeiwen.com/subject/ryuwektx.html