BlockingQueue |
1、简介
BlockingKQueue,阻塞队列。是一个队列,在多线程情况下,当需要入队而队列已满或需要出队而队列为空时,会造成阻塞,即线程挂起,一但入队或出队的条件满足,线程又自动唤醒。在消费者生产者问题中,可通过阻塞队列传递数据,当生产者消费者数据处理速度不一致时,例如,生产者速度大于消费者,当生产者的数据积累到一定程度时,就阻塞生产者线程,反之亦然。
2、BlockingKQueue的四组API
方式 | 抛出异常 | 有返回值,不抛出异常 | 阻塞等待 | 超时等待 |
---|---|---|---|---|
添加 | add(e) | offer() | put() | offer(…) |
移除 | remove(e) | poll() | take() | poll(…) |
检查队首元素 | element() | peek() | 无 | 无 |
代码示例:通过构造BlockingQueue的实现类ArrayBlockingQueue的对象来测试
第一组 |
public static void test1(){
BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue(2);
blockingQueue.add(1);
blockingQueue.add(2);
//blockingQueue.add(3); //超过队列大小,报IllegalStateException异常
System.out.println(blockingQueue.element());//查看队首元素
System.out.println("======================");
blockingQueue.remove();
blockingQueue.remove();
//blockingQueue.remove();// 移除不存在的元素,报NoSuchElementException异常
}
第二组 |
public static void test2(){
BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue(2);
blockingQueue.offer(1);
blockingQueue.offer(2);
//blockingQueue.offer(3);//不报错,返回false
System.out.println(blockingQueue.peek());//查看队首元素
System.out.println("======================");
blockingQueue.poll();
blockingQueue.poll();
//blockingQueue.poll();//不报错,返回null
}
第三组 |
public static void test3() throws InterruptedException {
BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue(2);
blockingQueue.put(1);
blockingQueue.put(2);
//blockingQueue.put(3);// 一直阻塞
System.out.println("======================");
blockingQueue.take();
blockingQueue.take();
//blockingQueue.take();// 一直阻塞
}
第四组 |
public static void test4() throws InterruptedException {
BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue(2);
blockingQueue.offer(1);
blockingQueue.offer(2);
//blockingQueue.offer(3,2, TimeUnit.SECONDS);//队列已满,等待2秒后退出
System.out.println("======================");
blockingQueue.poll();
blockingQueue.poll();
blockingQueue.poll(2, TimeUnit.SECONDS);//队列已空,等待2秒后退出
}
3、BlockingQueue的常用实现类
1、ArrayBlockingQueue
由数组结构组成的有界阻塞队列,容量是有限的,必须初始化容量。
2、LinkedBlockingQueue
由链表结构组成的无界阻塞队列,容量有限,默认容量为Integer.MAX_VALUE
3、PriorityBlockingQueue
支持优先级的无界阻塞队列
4、DelayQueue
使用优先级队列实现的无界阻塞队列
5、SynchronousQueue
不存储元素的阻塞队列