首页  

BlockingQueue add offer put 区别     所属分类 java 浏览量 1012
阻塞队列添加元素的几个方法及区别 

boolean add(E e);
boolean offer(E e);
boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException;
void put(E e) throws InterruptedException;
 
public boolean add(E e) {
    if (offer(e))
        return true;
    else
        throw new IllegalStateException("Queue full");
}

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.
When using a capacity-restricted queue, it is generally preferable to use  offer.
 
当使用容量受限的队列时,通常最好使用offer

  
offer   
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, 
returning true  upon success and  false if no space is currently available.  
When using a capacity-restricted queue, this method is generally preferable to add, 
which can fail to insert an element only by throwing an exception.
  
  
boolean offer(E e, long timeout, TimeUnit unit)
Inserts the specified element into this queue, waiting up to the specified wait time if necessary for space to become available.
        
   
put
Inserts the specified element into this queue, waiting if necessary for space to become available.
    

例子 BlockingQueue q = new ArrayBlockingQueue<>(3); q.add("a"); q.add("b"); q.add("c"); // 队列满了 // 立即 返回 false boolean result = q.offer("d"); System.out.println("offer result "+result); // 等待 1秒后 返回 false result = q.offer("d",1,TimeUnit.SECONDS); System.out.println("offer with timeout result "+result); try { q.add("d"); }catch(Throwable e) { // java.lang.IllegalStateException: Queue full System.out.println("add error,"+e); } // put 方法会一直阻塞 q.put("d");
java中的队列介绍

上一篇     下一篇
字符集编码基础知识

时间管理法则20条

做好项目管理的七个技巧

dubbo注册过程简介

dubbo获取线程池等信息

dubbo SPI 机制简介