ArrayBlockingArray-四组API



import java.sql.Time;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

//阻塞队列
//写入:如果队列满了,必须阻塞等待
//读取:如果队列空了,必须阻塞等待生产
public class BlockingQueueDemo {
public static void main(String[] args) throws InterruptedException {
Test3();
}

//抛出异常
public static void Test(){
ArrayBlockingQueue queue = new ArrayBlockingQueue<>(3);
System.out.println(queue.add("a"));
System.out.println(queue.add("b"));
System.out.println(queue.add("c"));
//查看队首
System.out.println("队首元素" + queue.element());
//队列容量只有3,如果此时加入第4个,则会抛出Queue full异常
//System.out.println(queue.add("d"));

System.out.println(queue.remove());
System.out.println(queue.remove());
System.out.println(queue.remove());
//队列空了,再去取,抛出NoSuchElementException异常·
//System.out.println(queue.remove());
}

//不抛出异常
public static void Test1(){
ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
System.out.println(queue.offer("a"));
System.out.println(queue.offer("b"));
System.out.println(queue.offer("c"));
//查看队首
System.out.println("队首元素" + queue.peek());
//队列容量只有3,如果此时加入第4个,offer方法不抛出异常了
System.out.println(queue.offer("d"));

System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
//队列容量只有3,如果此时加入第4个,offer方法不抛出异常了
System.out.println(queue.poll());
}

//阻塞等待
public static void Test2() throws InterruptedException {
ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
queue.put("a");
queue.put("b");
queue.put("c");
//阻塞等待了
//queue.put("d");

queue.take();
queue.take();
queue.take();
}

//超时等待
public static void Test3() throws InterruptedException {
ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
System.out.println(queue.offer("a"));
System.out.println(queue.offer("b"));
System.out.println(queue.offer("c"));
//超过2秒就不等了,退出
queue.offer("d", 2, TimeUnit.SECONDS);

System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
//队列容量只有3,如果此时加入第4个,offer方法不抛出异常了
System.out.println(queue.poll(2, TimeUnit.SECONDS));
}
}
posted @ 2021-08-04 14:44  gdstcymc  阅读(56)  评论(0)    收藏  举报