阻塞佇列4組api
阿新 • • 發佈:2022-03-22
阻塞佇列4組api
方式 | 丟擲異常 | 有返回值,不丟擲異常 | 阻塞 等待 | 阻塞超時 |
---|---|---|---|---|
新增 | add | offer() | put() | offer(e,long time,TimeUnit) |
移除 | remove | poll() | take() | poll(long time,TimeUnit) |
檢測隊首元素 | element | peek | - | - |
package BlockingQueueA; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; /** * @author liu */ public class Demo01 { public static void main(String[] args) throws InterruptedException { Test04(); } /** * arrayBlockingQueue 佇列丟擲異常 * add、element、remove */ 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")); //檢測佇列首元素 BlockingQueue.element(); //IllegalStateException: Queue full //System.out.println(arrayBlockingQueue.add("d")); System.out.println("-----------------------------------"); System.out.println(BlockingQueue.remove()); System.out.println(BlockingQueue.remove()); System.out.println(BlockingQueue.remove()); //NoSuchElementException //System.out.println(arrayBlockingQueue.remove()); } /** * arrayBlockingQueue 佇列不丟擲異常 * offer、peek、poll */ 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")); //不報異常,返回boolean System.out.println(BlockingQueue.offer("d")); //檢測佇列首元素 System.out.println(BlockingQueue.peek()); System.out.println("-----------------------------------"); System.out.println(BlockingQueue.poll()); System.out.println(BlockingQueue.poll()); System.out.println(BlockingQueue.poll()); //不報異常,返回null System.out.println(BlockingQueue.poll()); } /** * arrayBlockingQueue 佇列一直阻塞 * put、take */ public static void Test03() throws InterruptedException { //佇列大小:3 ArrayBlockingQueue 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()); } /** * arrayBlockingQueue 佇列超時退出 * put、take */ public static void Test04() throws InterruptedException { ArrayBlockingQueue BlockingQueue = new ArrayBlockingQueue<>(3); BlockingQueue.offer("a"); BlockingQueue.offer("b"); BlockingQueue.offer("c"); //等待超時1秒就退出 BlockingQueue.offer("d",1, TimeUnit.SECONDS); System.out.println("------------------------"); System.out.println(BlockingQueue.poll()); System.out.println(BlockingQueue.poll()); System.out.println(BlockingQueue.poll()); //等待超時1秒就退出 BlockingQueue.poll(1,TimeUnit.SECONDS); } }