/**
- @Author: CYW
- @Date: 2020/11/19 21:42
- 阻塞队列BlockingQueue
- Queue的结构
-
Collection
-
-Queue
-
-Deque
-
-AbstractQueue
-
-BlockingQueue
-
-LinkedBlockingQueue
-
-ArrayBlockingQueue
-
层层递进,下面的是上面的孩子
*/
public class BlockingQueueTest {
public static void main(String[] args) throws InterruptedException {
//test01();
//test02();
//test03();
test04();
}
/**
* 第一种:队列已满(加不进去)或队列已空(取不出来),
* 抛出异常,添加add(),移出remove()
*/
public static void test01(){
//设置队列长度为3
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(3);
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
//System.out.println(blockingQueue.add("d"));//抛出异常,因为队列已满
System.out.println(blockingQueue.remove());//出队,返回出队的值,FIFO
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//System.out.println(blockingQueue.remove());//队列已空,抛出异常
}
/**
* 第二种:队列已满(返回false)或队列已空(返回null),
* 添加offer(),移出poll(),peek()检测队首元素是什么
*/
public static void test02(){
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(3);
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
//System.out.println(blockingQueue.offer("d"));//队列已满,返回false
System.out.println(blockingQueue.peek());//检测队首元素
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
//System.out.println(blockingQueue.poll());//队列已空,返回null
}
/**
* 第三种:队列已满(一直等待)或队列已空(一直等待),
* 等待阻塞
* 添加put(),移出take()
*/
public static void test03() throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(3);
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
//blockingQueue.put("d");//队列已满,一直等待,程序不停
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
//System.out.println(blockingQueue.take());//队列已空,一直等待,程序不停
}
/**
* 第四种:队列已满(超时等待,超时退出),队列已空(超时等待,超时退出),
* 添加offer(),移出poll(int a,TimeUnit,SECONDS)
*/
public static void test04() throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(3);
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
blockingQueue.offer("d",2, TimeUnit.SECONDS);//等待两秒钟队列还是没位置就不等
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
blockingQueue.poll(2,TimeUnit.SECONDS);//等待两秒钟队列依然为空就不等了
}
}