java LinkedBlockingQueue的用法

本文详细介绍了使用Java中的LinkedBlockingQueue进行元素的添加(add, put, offer)与移除(take, remove, poll)操作的不同方式及其特点。通过具体示例展示了每种方法在队列满或空时的行为差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

		for (int i = 0; i < 3; i++) {
			System.out.println("add "+i);
			try {
				queue.put(i + "");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		System.out.println("over...");
add 0
add 1
add 2

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

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

		for (int i = 0; i < 3; i++) {
			System.out.println("add "+i);
			queue.add(i + "");
		}
		
		System.out.println("over...");
add 0
add 1
add 2
Exception in thread "main" java.lang.IllegalStateException: Queue full
	at java.util.AbstractQueue.add(AbstractQueue.java:98)
	at testqueue.test.main(test.java:50)

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

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

		for (int i = 0; i < 3; i++) {
			System.out.println("add "+i);
			System.out.println(queue.offer(i + ""));;
		}
		
		System.out.println("over...");
add 0
true
add 1
true
add 2
false
over...

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

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

final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
		
		System.out.println("waiting for take 。。。");
		try {
			System.out.println("remove " + queue.take());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("take over。。。");
waiting for take 。。。

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

final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
		
		System.out.println("waiting for remove 。。。");
		System.out.println("remove " + queue.remove());
		System.out.println("remove over。。。");
waiting for remove 。。。
Exception in thread "main" java.util.NoSuchElementException
	at java.util.AbstractQueue.remove(AbstractQueue.java:117)
	at testqueue.test.main(test.java:49)

poll 如果队列为空会返回null

final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
		
		System.out.println("waiting for poll 。。。");
		System.out.println("remove " + queue.poll());
		System.out.println("poll over。。。");
waiting for poll 。。。
remove null
poll over。。。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值