阻塞队列
就好比如你去快餐店,如果没人买,老板东西做够了,他就要停止,等待客人买走,而如果客人太多,老板忙不过了,这时候客人就要等待老板生产!
阻塞队列:
BlockingQueue
什么情况下我们会使用 阻塞队列:
多线程情况下,A调用B,B要去先执行,A调用B要等待B先执行完! 还有线程池,除去它自身的弹性大小,一半还用阻塞队列进行维护。
学会使用队列
添加、移除
四组API (根据情况合理使用!)
方式 | 抛出异常 | 不抛,有返 | 阻塞等待 | 超时等待 |
---|---|---|---|---|
添加 | add() | offer() | put() | offer(,) |
移除 | remove() | pool() | take() | pool(,) |
判断队列首 | element | peek | - | - |
抛出异常代码示例:
public static void test1(){
// 放入队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
//添加三个,返回三个true
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
//添加超出队列大小的数据,会抛出异常 Queue full 队列已满!
//System.out.println(blockingQueue.add("d"));
System.out.println("===================弹出!");
//队列先进先出!
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
// 队列空了之后再去移除也会抛出异常 java.util.NoSuchElementException 没有元素
System.out.println(blockingQueue.remove());
}
有返回值,没有异常示例:(内涵判断队列首前两种方法!)
public static void test2(){
// 放入队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
//存放
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
// 不抛出异常,返回false
//System.out.println(blockingQueue.offer("d")); //false
//获取
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
//System.out.println(blockingQueue.element()); //返回队首元素 ,会抛出异常
//System.out.println(blockingQueue.peek()); //不抛出异常,返回null
//当队列空了,再取会返回null 不会抛出异常!
//System.out.println(blockingQueue.poll()); //null
}
等待,阻塞(一直阻塞)代码示例:
public static void test3() throws InterruptedException {
// 放入队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
// put 放入
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
//blockingQueue.put("d"); //队列没有位置了,他就会一直等,阻塞!
// take() 取出
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
//队列没有元素,就会一直等待取值,阻塞!
System.out.println(blockingQueue.take());
}
等待,阻塞(等待超时)代码示例:
public static void test4() throws InterruptedException {
// 放入队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.offer("a");
blockingQueue.offer("b");
blockingQueue.offer("c");
//等待两秒,你不给我让位置,我就超时退出!
blockingQueue.offer("d",2, TimeUnit.SECONDS);
System.out.println("===============");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
//等待两秒还等不到,我就不要了,退出!
blockingQueue.poll(2,TimeUnit.SECONDS);
}
可以去查看官方文档JUC下具体案例!