/**
* @author
* @date 2023/1/1 9:44
* 阻塞队列演示
*/
public class BlockingQueueDemo {
public static void main(String[] args) throws InterruptedException {
//第一组add 与 remove
//testAddAndRemove();
//第二组 offer 与 poll
//testOfferAndPoll();
//第三组 put 与 take
//testPutAndTake();
//第四组 offer 与 poll 设置超时时间
testOfferAndPollTimeout();
}
public static void testAddAndRemove(){
//创建阻塞队列
ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
//第一组add 与 remove
//添加元素
System.out.println(blockingQueue.add("a"));
//System.out.println(blockingQueue.element());
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
//System.out.println(blockingQueue.add("d"));//此时队列已满,会抛异常 IllegalStateException: Queue full
//移除元素
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//System.out.println(blockingQueue.remove());//此时队列为空 也会抛异常 oSuchElementException
}
public static void testOfferAndPoll(){
//创建阻塞队列
ArrayBlockingQueue<String> 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.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());//队列为空 返回null
}
public static void testPutAndTake() throws InterruptedException {
//创建阻塞队列
ArrayBlockingQueue<String> 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());//队列为空 进入阻塞
}
public static void testOfferAndPollTimeout() throws InterruptedException {
//创建阻塞队列
ArrayBlockingQueue<String> 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",3L, TimeUnit.SECONDS));//超时之后 返回false
//移除元素
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
//System.out.println(blockingQueue.poll(3L,TimeUnit.SECONDS));//超时之后 返回null
}
}
方法类型 | 抛出异常 | 特殊值 | 阻塞 | 超时 |
---|---|---|---|---|
插入 | add(e) | offer(e) | put(e) | offer(e,time,unit) |
移除 | remove() | poll() | take() | poll(time,unit) |
检查 | element() | peek() |