LinkedBlockingQueue的put,add跟offer的区别(转)

简介: LinkedBlockingQueue的put,add和offer的区别        最近在学习,有很多java.util.concurrent包下的新类。LinkedBlockingQueue就是其中之一,顾名思义这是一个阻塞的线程安全的队列,底层应该采用链表实现。

LinkedBlockingQueue的put,add和offer的区别 

      最近在学习<<Java并发编程实践>>,有很多java.util.concurrent包下的新类。LinkedBlockingQueue就是其中之一,顾名思义这是一个阻塞的线程安全的队列,底层应该采用链表实现。

       看其API的时候发现,添加元素的方法竟然有三个:add,put,offer。

且这三个元素都是向队列尾部添加元素的意思。于是我产生了兴趣,要仔细探究一下他们之间的差别。

1.首先看一下add方法:

    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. 

    This implementation returns true if offer succeeds, else throws an IllegalStateException.

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

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

public static void main(String args[]){
		try {
			LinkedBlockingQueue<String> queue=new LinkedBlockingQueue(2);
			
			queue.add("hello");
			queue.add("world");
			queue.add("yes");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
//运行结果:
java.lang.IllegalStateException: Queue full
	at java.util.AbstractQueue.add(Unknown Source)
	at com.wjy.test.GrandPather.main(GrandPather.java:12)

 

2.再来看一下put方法:

    Inserts the specified element at the tail of this queue, waiting if necessary for space to become available.

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

public static void main(String args[]){
		try {
			LinkedBlockingQueue<String> queue=new LinkedBlockingQueue(2);
			
			queue.put("hello");
			queue.put("world");
			queue.put("yes");
			
			System.out.println("yes");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
//运行结果:
//在queue.put("yes")处发生阻塞
//下面的“yes”无法输出

 

3.最后看一下offer方法:

     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。

 

public static void main(String args[]){
		try {
			LinkedBlockingQueue<String> queue=new LinkedBlockingQueue(2);
			
			boolean bol1=queue.offer("hello");
			boolean bol2=queue.offer("world");
			boolean bol3=queue.offer("yes");
			
			System.out.println(queue.toString());
			System.out.println(bol1);
			System.out.println(bol2);
			System.out.println(bol3);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
//运行结果:
[hello, world]
true
true
false

 

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

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

 

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

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

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

http://www.soso.io/article/66762.html

目录
相关文章
|
Java 开发者
Java SPI机制大揭秘:动态加载服务提供者,一文让你彻底解锁!
【8月更文挑战第25天】Java SPI(服务提供者接口)是一种强大的扩展机制,允许程序在运行时动态加载服务实现。本文首先介绍SPI的基本原理——定义接口并通过配置文件指定其实现类,随后通过示例演示其实现过程。接着,对比分析了SPI与反射及插件机制的不同之处,强调SPI在灵活性与扩展性方面的优势。最后,基于不同场景推荐合适的选择策略,帮助读者深入理解并有效利用SPI机制。
574 1
|
XML 存储 Android开发
Android实战经验之Kotlin中快速实现MVI架构
本文介绍MVI(Model-View-Intent)架构模式,强调单向数据流与不可变状态管理,提升Android应用的可维护性和可测试性。MVI分为Model(存储数据)、View(展示UI)、Intent(用户动作)、State(UI状态)与ViewModel(处理逻辑)。通过Kotlin示例展示了MVI的实现过程,包括定义Model、State、Intent及创建ViewModel,并在View中观察状态更新UI。
734 12
|
网络协议 API 数据格式
HTTP 和 TCP 协议的主要区别
【10月更文挑战第25天】HTTP 和 TCP 在网络通信中扮演着不同的角色,各自具有独特的功能和特点,它们相互配合,共同为实现网络应用的各种需求提供了基础支持。
|
人工智能 监控 Java
SpringBoot实战(十三):Spring Boot Admin 动态修改日志级别
SpringBoot实战(十三):Spring Boot Admin 动态修改日志级别
934 0
|
存储 安全 Java
从基础到实战:如何用 Java 手写一个阻塞队列?
大家好,我是小米!今天分享手写阻塞队列(Blocking Queue)教程,深入讲解并发编程中的 wait() 和 notifyAll() 机制,通过代码实战,让你轻松掌握生产者-消费者模型中的阻塞队列实现!
475 0
|
XML API Android开发
android S 上 安装apk出现android.os.FileUriExposedException
android S 上 安装apk出现android.os.FileUriExposedException
565 6
|
前端开发
【Netty 网络通信】ChannelFuture 解析
【1月更文挑战第9天】【Netty 网络通信】ChannelFuture 解析
|
编解码
RTP传输AAC
RTP传输AAC
546 1