LinkedBlockingQueue的put,add跟offer的区别

本文详细解析了Java并发包中LinkedBlockingQueue的add、put、offer三种添加元素方法的区别,并介绍了poll、remove、take三种从队列中取出元素的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LinkedBlockingQueue顾名思义这是一个阻塞的线程安全的队列,底层应该采用链表实现。 看其API的时候发现,添加元素的方法竟然有三个:add,put,offer。 且这三个方法都是向队列尾部添加元素的意思。于是我产生了兴趣,要仔细探究一下他们之间的差别。

1.首先看一下add方法:

[java]  view plain  copy
  1. Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.   
  2.   
  3. This implementation returns true if offer succeeds, else throws an IllegalStateException.  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.   
  2.   
  3. This implementation returns true if offer succeeds, else throws an IllegalStateException.  

        LinkedBlockingQueue构造的时候若没有指定大小,则默认大小为Integer.MAX_VALUE,当然也可以在构造函数的参数中指定大小。LinkedBlockingQueue不接受null。

       add方法在添加元素的时候,若超出了度列的长度会直接抛出异常:

[java]  view plain  copy
  1. public static void main(String args[]){  
  2.         try {  
  3.             LinkedBlockingQueue<String> queue=new LinkedBlockingQueue(2);  
  4.               
  5.             queue.add("hello");  
  6.             queue.add("world");  
  7.             queue.add("yes");  
  8.         } catch (Exception e) {  
  9.             // TODO: handle exception  
  10.             e.printStackTrace();  
  11.         }  
  12.     }  
  13. //运行结果:  
  14. java.lang.IllegalStateException: Queue full  
  15.     at java.util.AbstractQueue.add(Unknown Source)  
  16.     at com.wjy.test.GrandPather.main(GrandPather.java:12)  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public static void main(String args[]){  
  2.         try {  
  3.             LinkedBlockingQueue<String> queue=new LinkedBlockingQueue(2);  
  4.               
  5.             queue.add("hello");  
  6.             queue.add("world");  
  7.             queue.add("yes");  
  8.         } catch (Exception e) {  
  9.             // TODO: handle exception  
  10.             e.printStackTrace();  
  11.         }  
  12.     }  
  13. //运行结果:  
  14. java.lang.IllegalStateException: Queue full  
  15.     at java.util.AbstractQueue.add(Unknown Source)  
  16.     at com.wjy.test.GrandPather.main(GrandPather.java:12)  

 

2.再来看一下put方法:

[java]  view plain  copy
  1. Inserts the specified element at the tail of this queue, waiting if necessary for space to become available.  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Inserts the specified element at the tail of this queue, waiting if necessary for space to become available.  

      对于put方法,若向队尾添加元素的时候发现队列已经满了会发生阻塞一直等待空间,以加入元素。

[java]  view plain  copy
  1. public static void main(String args[]){  
  2.         try {  
  3.             LinkedBlockingQueue<String> queue=new LinkedBlockingQueue(2);  
  4.               
  5.             queue.put("hello");  
  6.             queue.put("world");  
  7.             queue.put("yes");  
  8.               
  9.             System.out.println("yes");  
  10.         } catch (Exception e) {  
  11.             // TODO: handle exception  
  12.             e.printStackTrace();  
  13.         }  
  14.     }  
  15. //运行结果:  
  16. //在queue.put("yes")处发生阻塞  
  17. //下面的“yes”无法输出  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public static void main(String args[]){  
  2.         try {  
  3.             LinkedBlockingQueue<String> queue=new LinkedBlockingQueue(2);  
  4.               
  5.             queue.put("hello");  
  6.             queue.put("world");  
  7.             queue.put("yes");  
  8.               
  9.             System.out.println("yes");  
  10.         } catch (Exception e) {  
  11.             // TODO: handle exception  
  12.             e.printStackTrace();  
  13.         }  
  14.     }  
  15. //运行结果:  
  16. //在queue.put("yes")处发生阻塞  
  17. //下面的“yes”无法输出  

 

3.最后看一下offer方法:

[java]  view plain  copy
  1. Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and false if this queue is full. When using a capacity-restricted queue, this method is generally preferable to method add, which can fail to insert an element only by throwing an exception.  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and false if this queue is full. When using a capacity-restricted queue, this method is generally preferable to method add, which can fail to insert an element only by throwing an exception.  

   

    offer方法在添加元素时,如果发现队列已满无法添加的话,会直接返回false。

 

[java]  view plain  copy
  1. public static void main(String args[]){  
  2.         try {  
  3.             LinkedBlockingQueue<String> queue=new LinkedBlockingQueue(2);  
  4.               
  5.             boolean bol1=queue.offer("hello");  
  6.             boolean bol2=queue.offer("world");  
  7.             boolean bol3=queue.offer("yes");  
  8.               
  9.             System.out.println(queue.toString());  
  10.             System.out.println(bol1);  
  11.             System.out.println(bol2);  
  12.             System.out.println(bol3);  
  13.         } catch (Exception e) {  
  14.             // TODO: handle exception  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
  18. //运行结果:  
  19. [hello, world]  
  20. true  
  21. true  
  22. false  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public static void main(String args[]){  
  2.         try {  
  3.             LinkedBlockingQueue<String> queue=new LinkedBlockingQueue(2);  
  4.               
  5.             boolean bol1=queue.offer("hello");  
  6.             boolean bol2=queue.offer("world");  
  7.             boolean bol3=queue.offer("yes");  
  8.               
  9.             System.out.println(queue.toString());  
  10.             System.out.println(bol1);  
  11.             System.out.println(bol2);  
  12.             System.out.println(bol3);  
  13.         } catch (Exception e) {  
  14.             // TODO: handle exception  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
  18. //运行结果:  
  19. [hello, world]  
  20. true  
  21. true  
  22. false  

 

    好了,竟然说了这么多了,就把从队列中取元素的方法也顺便一说。

从队列中取出并移除头元素的方法有:poll,remove,take。

 

poll: 若队列为空,返回null。

remove:若队列为空,抛出NoSuchElementException异常。

take:若队列为空,发生阻塞,等待有元素。


转载地址:http://blog.youkuaiyun.com/zmx729618/article/details/52979616 

### LinkedBlockingDeque 和 LinkedBlockingQueue 的主要区别 #### 数据结构设计 `LinkedBlockingQueue` 是一种基于链表的阻塞队列,允许在构造时指定其容量上限。如果不指定,默认容量为 `Integer.MAX_VALUE`。它的内部实现是一个单向链表[^2]。 相比之下,`LinkedBlockingDeque` 则是一种双端阻塞队列(deque),支持从两端进行插入和移除操作。这意味着它可以作为栈或者队列来使用,提供了更多的灵活性。其底层同样采用双向链表实现[^1]。 #### 功能特性对比 - **单一方向 vs 双向操作** - `LinkedBlockingQueue` 主要提供标准的一端入队另一端出队的功能。 - 而 `LinkedBlockingDeque` 不仅能像普通队列一样在一端添加元素并从另一端取出,还可以从前端或后端任意一端执行 push/pop 或 add/remove 操作[^4]。 - **线程安全性机制** 两者都具备良好的线程安全性能,并通过锁控制访问冲突情况下的资源竞争问题。不过由于 `LinkedBlockingDeque` 提供更多种可能的操作模式,所以在某些特殊情况下可能会稍微复杂一点处理逻辑上的互斥关系[^3]。 #### 使用场景分析 当只需要简单的先进先出(FIFO)行为时可以选择 `LinkedBlockingQueue`;但如果应用程序需要更加灵活的数据存取方式比如既要做到FIFO又要偶尔做LIFO(last-in-first-out),那么就应该考虑选用 `LinkedBlockingDeque`. 以下是两个类的部分核心方法列表比较: | 方法名 | 描述 | 存在于哪个类? | |----------------|----------------------------------------------------------------------------------------|-------------------------| | offer(e) | 将指定元素加入队列尾部 | Both | | poll() | 获取并移除头部元素 | Both | | peek() | 查看但不移除头部元素 | Both | | put(e) | 如果必要则等待空间可用后再放入 | Both | | take() | 如果必要则等待直到有元素可获取 | Both | | addFirst(e) | 添加至开头 | Only LBD | | removeLast() | 删除最后一个 | Only LBD | ```java // Example of using LinkedBlockingDeque as a stack. import java.util.concurrent.LinkedBlockingDeque; public class StackExample { public static void main(String[] args)throws Exception{ LinkedBlockingDeque<Integer> stack=new LinkedBlockingDeque<>(); // Push elements onto the 'stack' stack.push(1); stack.push(2); System.out.println(stack.pop()); // Outputs: 2 System.out.println(stack.pop()); // Outputs: 1 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值