LinkedBlockingQueue

Queue与Deque的区别:
       Queue单向队列,先进先出。 
       Deque 双向队列

ArrayBlockingQueue和LinkedBlockingQueue的区别:
       1.ArrayBlockingQueue定长的缓冲队列;LinkedBlockingQueue 无界的缓冲队列。
       2.队列中锁的实现不同:ArrayBlockingQueue实现的队列中的锁是没有分离的,即生产和消费用的是同一个锁;LinkedBlockingQueue实现的队列中的锁是分离的,即生产用的是putLock,消费是takeLock
       3.在生产或消费时操作不同:ArrayBlockingQueue实现的队列中在生产和消费的时候,是直接将元素插入或移除的;LinkedBlockingQueue实现的队列中在生产和消费的时候,需要把元素转换为Node<E>进行插入或移除,会影响性能。
       4.队列大小初始化方式不同:ArrayBlockingQueue实现的队列中必须指定队列的大小;LinkedBlockingQueue实现的队列中可以不指定队列的大小,默认是Integer.MAX_VALUE


注意: 

       1、在使用LinkedBlockingQueue时,若用默认大小且当生产速度大于消费速度时候,有可能会内存溢出。 
       2、在使用ArrayBlockingQueue和LinkedBlockingQueue分别对1000000个简单字符做入队操作时,LinkedBlockingQueue的消耗是ArrayBlockingQueue消耗的10倍左右, 
       即LinkedBlockingQueue消耗在1500毫秒左右,ArrayBlockingQueue只需150毫秒左右。

简单示例:
BlockingQueue<String> queue = new LinkedBlockingQueue<>(2);
boolean addOK = queue.add("a");// will throw IllegalStateException when Queue is full
try {
    queue.put("b");// will blocking when Queue is full

    addOK = queue.offer("c");// will not blocking when Queue is full
    System.out.println(addOK);

    addOK = queue.offer("d", 1, TimeUnit.SECONDS);//will blocking the times when Queue is full
    System.out.println(addOK);
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println(queue);

try {
    String value = queue.take(); // will blocking when Queue is empty
    value =  queue.poll();//// will not blocking when Queue is empty, return null if empty
    value =  queue.poll(1, TimeUnit.SECONDS);//will blocking the times when Queue is empty, return null if empty

    queue.peek();//Retrieves, but does not remove, the head of this queue,null if this queue is empty

} catch (InterruptedException e) {
    e.printStackTrace();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值