多线程——LinkedBlockingQueue的put、add跟offer的区别

1. LinkedBlockingQueue的添加:add和offer的区别


       eg: BlockingQueue<A> queue = new LinkedBlockingQueue<A>(CAPACITY);

LinkedBlockingQueue是java.util.concurrent包下的新类。顾名思义是一个阻塞的线程安全的队列,底层应该采用链表实现。

LinkedBlockingQueue添加元素的方法有三个:add、put、offer。且都是向队列尾部添加元素。

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

1.1 add添加

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

    public static void main(String args[]){  
            try {  
                LinkedBlockingQueue<String> queue = new LinkedBlockingQueue(1);  
                  
                queue.add("hello");  
                queue.add("world");   
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }

    //运行结果:  
    java.lang.IllegalStateException: Queue full 

 

1.2 put添加

put方法向队尾添加元素时若超出长度,则一直阻塞等待空间,直到能添加元素。

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

 

1.3 offer添加

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

    public static void main(String args[]){  
            try {  
                LinkedBlockingQueue<String> queue=new LinkedBlockingQueue(1);  
                  
                boolean bool1=queue.offer("hello");  
                boolean bool2=queue.offer("world");  
 
                  
                System.out.println(queue.toString());  
                System.out.println(bool1);  
                System.out.println(bool2);   
            } catch (Exception e) {   
                e.printStackTrace();  
            }  
        }  
    //运行结果:  
    [hello]  
    true   
    false  

 

2. LinkedBlockingQueue的移除:poll、remove和take

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

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

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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值