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

时间:2025-03-17 21:00:55

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


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

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

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);  
                  
                ("hello");  
                ("world");   
            } catch (Exception e) {  
                ();  
            }  
        }

    //运行结果:  
    : Queue full 

 

1.2 put添加

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

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

 

1.3 offer添加

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

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

 

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

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

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

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