Queue主要方法的区别:

  抛出异常 返回特殊值
插入 add(e)插入成功则返回true,没有可用空间则IllegalStateException offer(e)
移除 remove(e)获取并移除,不存在则抛异常 poll(e)
检查 element()获取元素,但并不移除,队列为空则抛出异常 peek()

Queue既可以是FIFO,也可以是按照一定优先级顺序排列,BlockingQueue区别在于对于空队列获取等待,满队列加入等待,适用于生产者消费者模型:

/**
* Created by itworker365 on 6/2/2017.
*/
public class ThreadWNTest {
public static void main (String[] args) throws InterruptedException {
BlockingQueue blockingQueue = new ArrayBlockingQueue(10);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
int i = 0;
while (i < 100) {
System.out.println("put :" + i++);
blockingQueue.put(i++);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
System.out.println("take: " + blockingQueue.take());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t2.start();
System.out.println("start");
}
}

ArrayBlockingQueue: 主要方法学习

包含一个object数组存放元素,takeIndex和putIndex分别包含放入和取出元素的位置,count表示当前元素个数,全局锁lock分别创建notFull和notEmpty(await/singnal)完成当元素满时添加等待,元素空时取元素等待。

class BasicBlockingQueue<E> {
final Object[] items;
int takeIndex;
int putIndex;
int count;
final ReentrantLock lock;
private final Condition notEmpty;
private final Condition notFull; public BasicBlockingQueue (int capacity, boolean fair){
this.items = new Object[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
//添加元素,如果添加元素为null则抛出异常,如果非null则获取全局锁
// 看添加元素后是否满足队列总长度限制,超出返回false,未超出则将元素添加到对应的items[putIndex]位置,并唤醒notEmpty.signal()
private boolean offer(E e) {
if (e == null)
throw new NullPointerException();
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (count == items.length)
return false;
else {
enqueue(e);
return true;
}
} finally {
lock.unlock();
}
}
//带超时设定的这种
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
if (e == null)
throw new NullPointerException();
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();
}
}
//添加元素时,offer如果满了返回false,而add不能添加时则抛出异常
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
} private void enqueue(E x) {
final Object[] items = this.items;
items[putIndex] = x;
if (++putIndex == items.length)
putIndex = 0;
count++;
notEmpty.signal();
}
//取出元素,带超时的,获取全局锁,当元素为0,等待超时时间,一直没有就返回null,有的话就取出队列元素
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();
}
} private E dequeue() {
final Object[] items = this.items;
E x = (E) items[takeIndex];
items[takeIndex] = null;
//不断循环使用
if (++takeIndex == items.length)
takeIndex = 0;
count--;
notFull.signal();
return x;
}
}

LinkedBlockingQueue: 主要方法学习

元素存放在单向列表中,记录首尾节点,统计元素数目用atomicInteger,takelock和putlock分离,添加只需要修改last,取出只需要修改head

class BasicLinkedBlockingQueue<E> {
private final int capacity = Integer.MAX_VALUE;
//统计元素数目用AtomicInteger
private final AtomicInteger count = new AtomicInteger(0);
private transient Node<E> head;
private transient Node<E> last;
//分别创建takeLock和putLock
private final ReentrantLock takeLock = new ReentrantLock();
private final Condition notEmpty = takeLock.newCondition(); private final ReentrantLock putLock = new ReentrantLock();
private final Condition notFull = putLock.newCondition(); //加入元素,包含超时,先获取putlock,跟array基本一样,元素数目用count.getAndIncrement()统计,然后释放锁,发放signalNotEmpty通知
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException { if (e == null) throw new NullPointerException();
long nanos = unit.toNanos(timeout);
int c = -1;
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly();
try {
while (count.get() == capacity) {
if (nanos <= 0)
return false;
nanos = notFull.awaitNanos(nanos);
}
enqueue(new Node<E>(e));
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
return true;
}
//取得元素,带超时,先拿到takelock,和别的也一样
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
E x = null;
int c = -1;
long nanos = unit.toNanos(timeout);
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly();
try {
while (count.get() == 0) {
if (nanos <= 0)
return null;
nanos = notEmpty.awaitNanos(nanos);
}
x = dequeue();
c = count.getAndDecrement();
if (c > 1)
notEmpty.signal();
} finally {
takeLock.unlock();
}
if (c == capacity)
signalNotFull();
return x;
}
//添加只需要修改last
private void enqueue(Node<E> node) {
last = last.next = node;
}
//取出只需要修改head
private E dequeue() {
Node<E> h = head;
Node<E> first = h.next;
h.next = h; // help GC
head = first;
E x = first.item;
first.item = null;
return x;
}
private void signalNotEmpty() {
final ReentrantLock takeLock = this.takeLock;
takeLock.lock();
try {
notEmpty.signal();
} finally {
takeLock.unlock();
}
}
private void signalNotFull() {
final ReentrantLock putLock = this.putLock;
putLock.lock();
try {
notFull.signal();
} finally {
putLock.unlock();
}
}
}
class Node<E> {
E item;
Node<E> next;
Node(E x) { item = x; }
}

各种Queue分析的更多相关文章

  1. jQuery.queue源码分析

    作者:禅楼望月(http://www.cnblogs.com/yaoyinglong ) 队列是一种特殊的线性表,它的特殊之处在于他只允许在头部进行删除,在尾部进行插入.常用来表示先进先出的操作(FI ...

  2. RabbitMQ的Vhost,Exchange,Queue原理分析

    Vhost分析 RabbitMQ的Vhost主要是用来划分不同业务模块.不同业务模块之间没有信息交互. Vhost之间相互完全隔离,不同Vhost之间无法共享Exchange和Queue.因此Vhos ...

  3. leetcode:Implement Stack using Queues 与 Implement Queue using Stacks

    一.Implement Stack using Queues Implement the following operations of a stack using queues. push(x) - ...

  4. 一步步实现windows版ijkplayer系列文章之三——Ijkplayer播放器源码分析之音视频输出——音频篇

    一步步实现windows版ijkplayer系列文章之一--Windows10平台编译ffmpeg 4.0.2,生成ffplay 一步步实现windows版ijkplayer系列文章之二--Ijkpl ...

  5. ffplay源码分析1-概述

    本文为作者原创,转载请注明出处:https://www.cnblogs.com/leisure_chn/p/10301215.html ffplay是一个很简单的播放器,但是初次接触仍会感到概念和细节 ...

  6. LeetCode(232) Implement Queue using Stacks

    题目 Implement the following operations of a queue using stacks. push(x) – Push element x to the back ...

  7. IOS GCD 使用 (二)

     上一节,主要介绍了GCD的基本的概念,这节将用代码深入详细介绍GCD的使用. 一  使用介绍    GCD的使用主要分为三步:创建代码块;选择或创建合适的分发队列;(同步.异步方式)向分发队列提交任 ...

  8. Java 容器源码分析之Queue

    简介 Queue是一种很常见的数据结构类型,在java里面Queue是一个接口,它只是定义了一个基本的Queue应该有哪些功能规约.实际上有多个Queue的实现,有的是采用线性表实现,有的基于链表实现 ...

  9. Python 源码分析:queue 队列模块

    起步 queue 模块提供适用于多线程编程的先进先出(FIFO)数据结构.因为它是线程安全的,所以多个线程很轻松地使用同一个实例. 源码分析 先从初始化的函数来看: 从这初始化函数能得到哪些信息呢?首 ...

随机推荐

  1. 【ZZ】终于有人把云计算、大数据和人工智能讲明白了!

    终于有人把云计算.大数据和人工智能讲明白了! https://mp.weixin.qq.com/s/MqBP0xziJO-lPm23Bjjh9w 很不错的文章把几个概念讲明白了...图片拷不过来... ...

  2. 廖雪峰Java2面向对象编程-4抽象类和接口-1抽象类

    每个子类都可以覆写父类的方法 如果父类的方法没有实际意义,能否去掉方法的执行语句?子类会报编译错误 如果去掉父类的方法,就失去了多态的特性 可以把父类的方法声明为抽象方法. 如果一个class定义了方 ...

  3. 廖雪峰Java2面向对象编程-1面向对象-1面向对象基础

    1.对象的概念 面向对象编程:Object-Oriented Programming 对现实世界建立计算机模型的一种编程方法. 现实世界 计算机模型 Java代码 人 类/class class Pe ...

  4. convert 批量文件的格式转换

    1.将 a.gif 转为 png 格式 convert a.gif a.png 请注意,convert 命令的基本格式为 convert 源文件 [参数] 目标文件 在上面的命令中,源文件是 a.gi ...

  5. [UE4]函数和事件的区别

    一.函数有返回值,事件无返回值 二.函数调用会等待函数执行结果,事件调用只是触发但不会等待. 三.函数执行在同一个线程,事件执行在不同线程. 四.函数可以用局部变量,事件没有局部变量. 五.因为函数执 ...

  6. 阿里云ECS搭建FTP服务器

    一.开始前先开通21端口权限; 二.添加IIS角色; 三.添加ftp用户; 四.步骤如下: 五.用添加在用户登录ftp;

  7. mysql视图 触发器 事物 函数 存储过程

    一 视图 视图是一个虚拟表(非真实存在),其本质是[根据SQL语句获取动态的数据集,并为其命名],用户使用时只需使用[名称]即可获取结果集,可以将该结果集当做表来使用. 使用视图我们可以把查询过程中的 ...

  8. Java - 32 Java 多线程编程

    Java 多线程编程 Java给多线程编程提供了内置的支持.一个多线程程序包含两个或多个能并发运行的部分.程序的每一部分都称作一个线程,并且每个线程定义了一个独立的执行路径. 多线程是多任务的一种特别 ...

  9. IIS7.5和IIS8如何设置FTP的pasv端口范围

    如果不设置端口范围,在防火墙开启的情况下,连接FTP时可能出现列表错误的现象,下面介绍下如何设置FTP的pasv端口范围.. 一.首先打开IIS选择服务器会进入全局设置,再双击FTP防火墙支持 二.设 ...

  10. 微信小程序开发warning: Now you can provide attr "wx:key" for a "wx:for" to improve performance

    用微信官方的模板发现突然报了这个warning,检查原因: 官方解释: wx:key 如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如 <i ...