java LinkedBlockingQueue的用法

参考:https://blog.csdn.net/caideb/article/details/81477631

1.加入元素,包含三种方式  put  add  offer

put 加入元素的时候如果队列已满则会阻塞等待

`

1.  final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
    

3.  		for (int i = 0; i < 3; i++) {
    
4.  			System.out.println("add "+i);
    
5.  			try {
    
6.  				queue.put(i + "");
    
7.  			} catch (InterruptedException e) {
    
8.  				// TODO Auto-generated catch block
    
9.  				e.printStackTrace();
    
10.  			}
    

12.  		}
    

14.  		System.out.println("over...");
    

`


`

1.  add 0
    
2.  add 1
    
3.  add 2
    

`


add加入元素的时候如果队列已满则会抛出异常

`

1.  final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
    

3.  		for (int i = 0; i < 3; i++) {
    
4.  			System.out.println("add "+i);
    
5.  			queue.add(i + "");
    
6.  		}
    

8.  		System.out.println("over...");
    

`


`

1.  add 0
    
2.  add 1
    
3.  add 2
    
4.  Exception in thread "main" java.lang.IllegalStateException: Queue full
    
5.  	at java.util.AbstractQueue.add(AbstractQueue.java:98)
    
6.  	at testqueue.test.main(test.java:50)
    

`


offer加入元素的时候如果队列已满则会返回false

`

1.  final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
    

3.  		for (int i = 0; i < 3; i++) {
    
4.  			System.out.println("add "+i);
    
5.  			System.out.println(queue.offer(i + ""));;
    
6.  		}
    

8.  		System.out.println("over...");
    

`


`

1.  add 0
    
2.  true
    
3.  add 1
    
4.  true
    
5.  add 2
    
6.  false
    
7.  over...
    

`


2.去除元素,包含三种方式take remove poll

take 如果队列为空则会阻塞等待

`

1.  final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
    

3.  		System.out.println("waiting for take 。。。");
    
4.  		try {
    
5.  			System.out.println("remove " + queue.take());
    
6.  		} catch (InterruptedException e) {
    
7.  			// TODO Auto-generated catch block
    
8.  			e.printStackTrace();
    
9.  		}
    
10.  		System.out.println("take over。。。");
    

`


`waiting for take 。。。`


remove 如果队列为空则会抛出异常

`

1.  final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
    

3.  		System.out.println("waiting for remove 。。。");
    
4.  		System.out.println("remove " + queue.remove());
    
5.  		System.out.println("remove over。。。");
    

`


`

1.  waiting for remove 。。。
    
2.  Exception in thread "main" java.util.NoSuchElementException
    
3.  	at java.util.AbstractQueue.remove(AbstractQueue.java:117)
    
4.  	at testqueue.test.main(test.java:49)
    

`


poll 如果队列为空会返回null

`

1.  final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
    

3.  		System.out.println("waiting for poll 。。。");
    
4.  		System.out.println("remove " + queue.poll());
    
5.  		System.out.println("poll over。。。");
    

`


`

1.  waiting for poll 。。。
    
2.  remove null
    
3.  poll over。。。
    

`


posted @ 2022-11-11 15:56  狂客  阅读(229)  评论(0编辑  收藏  举报