BlockingQueue阻塞隊列 BlockingQueue的四組API /**BlockQueue的四組API * 1.拋出異常 * 2.有返回值,不拋出異常 * 3.阻塞等待 * 4.超時等待 */public class BlockQueueTest { public static void ...
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()