阻塞队列BlockingQueue
使用场景
多线程并发处理,线程池
使用方法
添加,移除
四组API(应用程序接口)
1. add和remove(会抛出异常),检测队列首个元素(element)
/*
* 会抛出异常
*
* */
public static void test1(){
//capacity:队列容量
ArrayBlockingQueue<Object> blockingqueue = new ArrayBlockingQueue<>(3);
//添加队列
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("第一个元素为"+blockingqueue.element());
//取出队列
System.out.println(blockingqueue.remove());
System.out.println(blockingqueue.remove());
System.out.println(blockingqueue.remove());
//NoSuchElementException 没有元素
//System.out.println(blockingqueue.remove());
}
2. offer,poll(不会抛出异常),检测队列首个元素(peek)
/*
* 不会抛出异常
*
* */
public static void test2(){
//capacity:队列容量
ArrayBlockingQueue<Object> blockingqueue = new ArrayBlockingQueue<>(3);
//插入元素
System.out.println(blockingqueue.offer("a"));
System.out.println(blockingqueue.offer("b"));
System.out.println(blockingqueue.offer("c"));
//如果没有插入成功就返回false,插入成功就返回true
System.out.println(blockingqueue.offer("d"));
System.out.println("第一个元素为"+blockingqueue.peek());
//取出元素
System.out.println(blockingqueue.poll());
System.out.println(blockingqueue.poll());
System.out.println(blockingqueue.poll());
//有元素就取出相应的元素(先进先出FIFO),如果没有就返回null
System.out.println(blockingqueue.poll());
}
3.阻塞等待(一直等,等到天荒地老)put,take
/*
* 阻塞等待
*
* */
public static void test3() throws InterruptedException {
//capacity:队列容量
ArrayBlockingQueue<Object> blockingqueue = new ArrayBlockingQueue<>(3);
blockingqueue.put("a");
blockingqueue.put("a");
blockingqueue.put("a");
//程序卡在这里了,程序不会运行了(要避免发生这样的情况)
//blockingqueue.put("a");
System.out.println(blockingqueue.take());
System.out.println(blockingqueue.take());
System.out.println(blockingqueue.take());
//没有第四个元素,所以一直会等,等到第四个元素出现(但的四个元素不可能会出现)
System.out.println(blockingqueue.take());
}
4.延时等待(在限定的等待时间之内,如果没有等到对应的操作,就按照顺序执行代码)
public static void test4() throws InterruptedException {
//capacity:队列容量
ArrayBlockingQueue<Object> blockingqueue = new ArrayBlockingQueue<>(3);
blockingqueue.offer("a");
blockingqueue.offer("b");
blockingqueue.offer("c");
System.out.println("超额添加");
//等待两秒,如果队列还是阻塞的状态,就放弃添加,执行下面的代码
blockingqueue.offer("d",2, TimeUnit.SECONDS);
System.out.println("放弃添加");
System.out.println(blockingqueue.poll());
System.out.println(blockingqueue.poll());
System.out.println(blockingqueue.poll());
System.out.println("等待新元素添加");
//等待两秒,如果队列还没有添加新元素,就放弃获取元素
blockingqueue.poll(2,TimeUnit.SECONDS);
System.out.println("没有新元素的添加");
System.out.println("白");
}