Java 阻塞队列 BlockingQueue

阻塞队列:只是队列的拓展,传统队列当满的时候会抛出异常,而阻塞队列会一直等待,不会报错,当然,里面包含的方法如下:


  抛出异常 特殊值 阻塞 超时
插入 add(e) offer(e) put(e) offer(e, time, unit)
移除 remove() poll() take() poll(time, unit)
检查 element() peek() 不可用 不可用


我们发现添加方法有四种,我们这里分别演示一下效果,

add(e)

public class QueueDemo {
	public static void main(String[] args) throws InterruptedException {
		ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(20);
		for (int i = 0; i < 30; i++) {
			queue.add(i);
			// queue.offer(i);
			// queue.put(i);
			System.out.println("add number is --->" + i);
		}
		System.out.println("END");
	}
}
结果:

add number is --->0
add number is --->1
add number is --->2
add number is --->3
add number is --->4
add number is --->5
add number is --->6
add number is --->7
add number is --->8
add number is --->9
add number is --->10
add number is --->11
add number is --->12
add number is --->13
add number is --->14
add number is --->15
add number is --->16
add number is --->17
add number is --->18
add number is --->19
Exception in thread "main" java.lang.IllegalStateException: Queue full
	at java.util.AbstractQueue.add(Unknown Source)
	at java.util.concurrent.ArrayBlockingQueue.add(Unknown Source)
	at com.yonyou.thread.QueueDemo.main(QueueDemo.java:9)

开辟了size为20的队列,但是添加进去30个Integer对象,则超过临界区大小,抛出异常。

queue.offer(i);

add number is --->0
add number is --->1
add number is --->2
add number is --->3
add number is --->4
add number is --->5
add number is --->6
add number is --->7
add number is --->8
add number is --->9
add number is --->10
add number is --->11
add number is --->12
add number is --->13
add number is --->14
add number is --->15
add number is --->16
add number is --->17
add number is --->18
add number is --->19
add number is --->20
add number is --->21
add number is --->22
add number is --->23
add number is --->24
add number is --->25
add number is --->26
add number is --->27
add number is --->28
add number is --->29
END

结果正常输出,该方法放弃大小限制,无限制容量扩展。

Java 阻塞队列 BlockingQueue_第1张图片

到达临界区 放不进去了。。。队列处于阻塞状态。。。等待有空闲空间。


queue.offer(i, 2000, TimeUnit.MILLISECONDS);

结果也不会受到size大小限制,会根据我们提前设置好的2s  依次入队 结果没有影响。


你可能感兴趣的:(Java 阻塞队列 BlockingQueue)