package juc;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public class BlockingQueueDemo {
public static void main(String[] args) throws InterruptedException {
//创建阻塞队列-队列(先进先出)栈(后进先出)
BlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
//第一组add、remove抛异常element检查
first(blockingQueue);
//第二组offer、poll返回值false和null,peek检查
second(blockingQueue);
//第三组put、take阻塞
third(blockingQueue);
//第四组offer、poll多参数超时-阻塞-超时长返回值false和null
four(blockingQueue);
}
private static void first(BlockingQueue blockingQueue){
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
System.out.println(blockingQueue.element());
//System.out.println(blockingQueue.add("w"));//IllegalStateException: Queue full
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//System.out.println(blockingQueue.remove());//NoSuchElementException
}
private static void second(BlockingQueue blockingQueue){
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
System.out.println(blockingQueue.offer("www"));
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());
}
private static void third(BlockingQueue blockingQueue) throws InterruptedException {
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
//blockingQueue.put("w");
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
//System.out.println(blockingQueue.take());
}
private static void four(BlockingQueue blockingQueue) throws InterruptedException {
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
System.out.println(blockingQueue.offer("w",3L, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(3L, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(3L, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(3L, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(3L, TimeUnit.SECONDS));
}
}