BlockingQueue的四组API
/**BlockQueue的四组API
* 1.抛出异常
* 2.有返回值,不抛出异常
* 3.阻塞等待
* 4.超时等待
*/
public class BlockQueueTest {
public static void main(String[] args) throws InterruptedException {
test03();
}
/**抛出异常
* */
public static void test01(){
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.element());
//IllegalStateException: Queue full 抛出异常,列满
//blockingQueue.add(\"d\");
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//.NoSuchElementException 队空
//System.out.println(blockingQueue.remove());
}
/**不抛出异常,有返回值
* */
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.peek());
//有返回值,不抛出异常
// System.out.println(blockingQueue.offer(\"d\"));
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
//有返回值,不抛出异常
//System.out.println(blockingQueue.poll());
}
/**阻塞等待,一直阻塞
* */
public static void test03() throws InterruptedException {
ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(3);
arrayBlockingQueue.put(\"a\");
arrayBlockingQueue.put(\"b\");
arrayBlockingQueue.put(\"c\");
//队满,阻塞等待,一直等待
//arrayBlockingQueue.put(\"d\");
System.out.println(arrayBlockingQueue.take());
System.out.println(arrayBlockingQueue.take());
System.out.println(arrayBlockingQueue.take());
//队空,阻塞等待,一直等待
//System.out.println(arrayBlockingQueue.take());
}
/**
*超时等待,但不会一直等待,阻塞时间内等待,之后退出
*/
public static void test04() throws InterruptedException {