JDK各个队列基本特性比较

前言

阻塞队列和普通队列区别

  • 阻塞队列与普通队列的区别在于,当队列是空的时,从队列中获取元素的操作将会被阻塞,或者当队列是满时,往队列里添加元素的操作会被阻塞。试图从空的阻塞队列中获取元素的线程将会被阻塞,直到其他的线程往空的队列插入新的元素。同样,试图往已满的阻塞队列中添加新元素的线程同样也会被阻塞,直到其他的线程使队列重新变得空闲起来,如从队列中移除一个或者多个元素,或者完全清空队列.
  • ArrayDeque, (数组双端队列)
  • ArrayBlockingQueue, (基于数组的并发阻塞队列)
  • ConcurrentLinkedQueue, (基于链表的并发队列)
  • DelayQueue, (延期阻塞队列)(阻塞队列实现了BlockingQueue接口)
  • LinkedBlockingQueue, (基于链表的FIFO阻塞队列)
  • LinkedBlockingDeque, (基于链表的FIFO双端阻塞队列)
  • LinkedTransferQueue, (基于链表无界的阻塞队列)
  • PriorityQueue, (优先级队列)
  • PriorityBlockingQueue, (带优先级的无界阻塞队列)
  • SynchronousQueue (并发同步阻塞队列)


ArrayDeque


返回目录
api

继承体系

java.lang.Object
	java.util.AbstractCollection<E>
		java.util.ArrayDeque<E>

实现接口

Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, Queue<E>

构造器

ArrayDeque()
Constructs an empty array deque with an initial capacity sufficient to hold 16 elements.
ArrayDeque(Collection<? extends E> c)
Constructs a deque containing the elements of the specified collection, in the order they are returned by the collection's iterator.
ArrayDeque(int numElements)
Constructs an empty array deque with an initial capacity sufficient to hold the specified number of elements.

说明

  • 内部结构为数组
  • 无容量限制,可随添加数据自动扩容
    • 当 oldCapacity < 64;newCapacity = oldCapacity × 2 + 2
    • 当 oldCapacity >= 64;newCapacity = oldCapacity × 1.5
  • 非线程安全,不可并发访问
  • 迭代器带fail-fast特性,不可在迭代访问时进行修改
  • 双端队列,可在队头和队尾插入和获取元素,可用作LIFO或者FIFO队列。

常用方法

//插入元素
boolean	add(E e)
Inserts the specified element at the end of this deque.
void	addFirst(E e)
Inserts the specified element at the front of this deque.
void	addLast(E e)
Inserts the specified element at the end of this deque.
//插入元素 ,还是调用上面的add方法
boolean	offer(E e)
Inserts the specified element at the end of this deque.
boolean	offerFirst(E e)
Inserts the specified element at the front of this deque.
boolean	offerLast(E e)
Inserts the specified element at the end of this deque.
//获取元素,但是不删除元素
E	element()
Retrieves, but does not remove, the head of the queue represented by this deque.
E	getFirst()
Retrieves, but does not remove, the first element of this deque.
E	getLast()
Retrieves, but does not remove, the last element of this deque.
//获取元素并删除
E	poll()
Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.
E	pollFirst()
Retrieves and removes the first element of this deque, or returns null if this deque is empty.
E	pollLast()
Retrieves and removes the last element of this deque, or returns null if this deque is empty.

ArrayBlockingQueue


返回目录
api

继承体系

java.lang.Object
	java.util.AbstractCollection<E>
		java.util.AbstractQueue<E>
			java.util.concurrent.ArrayBlockingQueue<E>

实现接口

Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E>

构造器

说明


ConcurrentLinkedQueue


返回目录
api

返回目录

说明

继承体系

java.lang.Object
	java.util.AbstractCollection<E>
		java.util.AbstractQueue<E>
			java.util.concurrent.ConcurrentLinkedQueue<E>

实现接口

Serializable, Iterable<E>, Collection<E>, Queue<E>

构造器


DelayQueue


返回目录
api

继承体系

java.lang.Object
	java.util.AbstractCollection<E>
		java.util.AbstractQueue<E>
			java.util.concurrent.DelayQueue<E>

实现接口

Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E>

构造器

DelayQueue()
Creates a new DelayQueue that is initially empty.
DelayQueue(Collection<? extends E> c)
Creates a DelayQueue initially containing the elements of the given collection of Delayed instances.

说明

  • 延期阻塞队列
  • 内部使用PriorityQueue实现
  • 元素不能为null
  • 元素必须实现Delayed接口中的方法getDelay(TimeUnit unit)和接口Comparable中的方法compareTo(Delayed other)

实例

class DelayQueueModel implements Delayed {

    // 数据
    private String str;
    // 延时时间
    private long delayTime;
    // 到期时间
    private long timeOut;

    /**
     * 构造函数 到期时间 = 延时时间 - 当前系统时间
     * @param str 数据
     * @param timeOut 延迟时间
     */
    DelayQueueModel(String str,long timeOut){
        this.str = str;
        this.delayTime = timeOut;
        this.timeOut = timeOut + System.currentTimeMillis();
    }

    //返回距离你自定义的超时时间还有多少
    public long getDelay(TimeUnit unit){
        return unit.convert(timeOut - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    //比较getDelay()函数的返回值
    public int compareTo(Delayed other){
        if (other == this)
            return 0;
        DelayQueueModel delayQueueModel = (DelayQueueModel)other;
        long time = (getDelay(TimeUnit.MILLISECONDS) - delayQueueModel.getDelay(TimeUnit.MILLISECONDS));
        return (time == 0) ? 0 : ((time < 0) ? -1 : 1);
    }

    void print(){
        System.out.println("元素:" + str + "\t 延时时间:" + delayTime + "\t 过期时间:" + new Date(timeOut));
    }

}

public class DelayQueueDemo {

    public static void main(String[] args) {

        DelayQueue<DelayQueueModel> queue = new DelayQueue<>();
        for(int i = 0; i < 10; i++){
            DelayQueueModel delayQueueModel = new DelayQueueModel("第"+ (i + 1) +"个", 1000*(10-i));
            queue.put(delayQueueModel);
        }

        for(int i = 0; i < 15; i++){

            try {
                queue.take().print();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

输出
最先出队的是delay时间最小的元素,也就是最快过期的元素

元素:第10个	 延时时间:1000	 过期时间:Sat Dec 08 18:53:51 CST 2018
元素:第9个	 延时时间:2000	 过期时间:Sat Dec 08 18:53:52 CST 2018
元素:第8个	 延时时间:3000	 过期时间:Sat Dec 08 18:53:53 CST 2018
元素:第7个	 延时时间:4000	 过期时间:Sat Dec 08 18:53:54 CST 2018
元素:第6个	 延时时间:5000	 过期时间:Sat Dec 08 18:53:55 CST 2018
元素:第5个	 延时时间:6000	 过期时间:Sat Dec 08 18:53:56 CST 2018
元素:第4个	 延时时间:7000	 过期时间:Sat Dec 08 18:53:57 CST 2018
元素:第3个	 延时时间:8000	 过期时间:Sat Dec 08 18:53:58 CST 2018
元素:第2个	 延时时间:9000	 过期时间:Sat Dec 08 18:53:59 CST 2018
元素:第1个	 延时时间:10000	 过期时间:Sat Dec 08 18:54:00 CST 2018


LinkedBlockingQueue


返回目录
api

说明

继承体系

java.lang.Object
	java.util.AbstractCollection<E>
		java.util.AbstractQueue<E>
			java.util.concurrent.LinkedBlockingQueue<E>

实现接口

	Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E>

LinkedBlockingDeque


返回目录
api

继承体系

java.lang.Object
	java.util.AbstractCollection<E>
		java.util.AbstractQueue<E>
			java.util.concurrent.LinkedBlockingDeque<E>

实现接口

	Serializable, Iterable<E>, Collection<E>, 
	BlockingDeque<E>, BlockingQueue<E>, Deque<E>, Queue<E>

说明


LinkedTransferQueue


返回目录
api

继承体系

java.lang.Object
	java.util.AbstractCollection<E>
		java.util.AbstractQueue<E>
			java.util.concurrent.LinkedTransferQueue<E>

实现接口

Serializable, Iterable<E>, Collection<E>,
 BlockingQueue<E>, TransferQueue<E>, Queue<E>

构造器

LinkedTransferQueue()
//Creates an initially empty LinkedTransferQueue.
LinkedTransferQueue(Collection<? extends E> c)
//Creates a LinkedTransferQueue initially containing the elements
// of the given collection, added in traversal order of the
//  collection's iterator.

说明

  • 基于链表无界的阻塞队列(FIFO)
  • 使用CAS算法保证线程安全
  • 元素不允许为null
  • size()需要遍历队列才能计算时间,并且不一定保证实时正确,因为遍历过程中元素数量可能会改变。
  • add(E e) ,向队尾插入元素,不阻塞,永远返回true
  • take(),尝试获取并删除队头元素,如果队列为空,则阻塞等待
  • TransferQueue接口
    • tryTransfer(E):将元素立刻给消费者。准确的说就是立刻给一个等待接收元素的线程,如果没有消费者就会返回false,而不将元素放入队列
    • transfer(E):将元素给消费者,如果没有消费者就会等待。
    • tryTransfer(E,long,TimeUnit):将元素立刻给消费者,如果没有就等待指定时间。给失败返回false
    • hasWaitingConsumer():返回当前是否有消费者在等待元素。
    • getWaitingConsumerCount():返回等待元素的消费者个数。

PriorityQueue


[返回目录](#head) [api](https://docs.oracle.com/javase/8/docs/api/)

继承体系

java.lang.Object
    java.util.AbstractCollection<E>
       java.util.AbstractQueue<E>
          java.util.PriorityQueue<E>

实现接口

Serializable, Iterable<E>, Collection<E>, Queue<E>

构造器

PriorityQueue()
//Creates a PriorityQueue with the default initial capacity (11) 
//that orders its elements according to their natural ordering.
PriorityQueue(Collection<? extends E> c)
//Creates a PriorityQueue containing the elements in the 
//specified collection.
PriorityQueue(Comparator<? super E> comparator)
//Creates a PriorityQueue with the default initial capacity
// and whose elements are ordered according to the specified comparator.
PriorityQueue(int initialCapacity)
//Creates a PriorityQueue with the specified initial capacity that orders
// its elements according to their natural ordering.
PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
//Creates a PriorityQueue with the specified initial capacity
 //that orders its elements according to the specified comparator.
PriorityQueue(PriorityQueue<? extends E> c)
//Creates a PriorityQueue containing the elements
// in the specified priority queue.
PriorityQueue(SortedSet<? extends E> c)
//Creates a PriorityQueue containing the elements 
//in the specified sorted set.

说明

  • 无界有序的阻塞队列
  • 内部使用数组保存元素,平衡二叉堆实现排序
  • 非线程安全
  • 队列元素要么实现Comparable接口,要么构造器传入自定义的Comparator对象,使用这两个接口来实现排序
  • 不允许null元素
  • 提供Iterator和Spliterator迭代器,但是迭代器访问不是排序的,如果要排序只能使用Arrays.sort(pq.toArray())来实现
  • 无容量限制,可随添加数据自动扩容
    • 当 oldCapacity < 64;newCapacity = oldCapacity × 2 + 2
    • 当 oldCapacity >= 64;newCapacity = oldCapacity × 1.5

PriorityBlockingQueue


API
返回目录

继承体系

java.lang.Object
	java.util.AbstractCollection<E>
		java.util.AbstractQueue<E>
			java.util.concurrent.PriorityBlockingQueue<E>

实现接口

Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E>

构造器

PriorityBlockingQueue()
Creates a PriorityBlockingQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
PriorityBlockingQueue(Collection<? extends E> c)
Creates a PriorityBlockingQueue containing the elements in the specified collection.
PriorityBlockingQueue(int initialCapacity)
Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to their natural ordering.
PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator)
Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified comparator.

说明

  • 无界有序的阻塞队列
  • 内部使用数组保存元素,平衡二叉堆实现排序
  • 使用ReentrantLock和CAS保证并发访问
  • 队列元素要么实现Comparable接口,要么构造器传入自定义的Comparator对象,使用这两个接口来实现排序
  • 不允许null元素
  • 提供Iterator和Spliterator迭代器,但是迭代器访问不是排序的,如果要排序只能使用Arrays.sort(pq.toArray())来实现
  • 从队列中获取到的元素是排好序的
  • 初始默认容量为11
  • 无容量限制,可随添加数据自动扩容
    • 当 oldCapacity < 64;newCapacity = oldCapacity × 2 + 2
    • 当 oldCapacity >= 64;newCapacity = oldCapacity × 1.5

SynchronousQueue


返回目录

继承体系

java.lang.Object
	java.util.AbstractCollection<E>
		java.util.AbstractQueue<E>
			java.util.concurrent.SynchronousQueue<E>

实现接口

Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E>

构造器

SynchronousQueue()
Creates a SynchronousQueue with nonfair access policy.
SynchronousQueue(boolean fair)
Creates a SynchronousQueue with the specified fairness policy.

说明

  • 阻塞队列,其中每个 put 必须等待一个 take,反之亦然。同步队列没有任何内部容量,甚至连一个队列的容量都没有;
  • 不允许null元素
  • 使用ReentrantLock和CAS来保证线程安全
  • 默认为非公平策略,可在构造器中配置
  • iterator() 永远返回空,因为里面没东西。
  • peek() 永远返回null。
  • put() 往queue放进去一个element以后就一直wait直到有其他thread进来把这个element取走。
  • offer() 往queue里放一个element后立即返回,如果碰巧这个element被另一个thread取走了,offer方法返回true,认为offer成功;否则返回false。
  • offer(2000, TimeUnit.SECONDS) 往queue里放一个element但是等待指定的时间后才返回,返回的逻辑和offer()方法一样。
  • take() 取出并且remove掉queue里的element(认为是在queue里的。。。),取不到东西他会一直等。
  • poll() 取出并且remove掉queue里的element(认为是在queue里的。。。),只有到碰巧另外一个线程正在往queue里offer数据或者put数据的时候,该方法才会取到东西。否则立即返回null。
  • poll(2000, TimeUnit.SECONDS) 等待指定的时间然后取出并且remove掉queue里的element,其实就是再等其他的thread来往里塞。
  • isEmpty()永远是true。
  • remainingCapacity() 永远是0。
  • remove()和removeAll() 永远是false。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值