1.队列家族
写入时,如果队列满了,就必须 阻塞等待
取出时,如果队列是空的,就必须阻塞等待生产
2.什么情况下需要阻塞等待?
多线程并发处理,线程池
3.四组API
1.抛出异常
import java.util.concurrent.ArrayBlockingQueue;
public class Test {
public static void main(String[] args) {
test1();
//抛出异常
}
public static void test1(){
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.remove());//删除元素
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
}
}
添加3个元素,删除第4个元素时,会抛出异常
2.不会抛出异常,有返回值
public static void test2(){
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.offer("d"));
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());//删除元素
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
}
添加3个元素,删除第4个元素时,会返回false。
3.阻塞等待
public static void test3() throws InterruptedException {
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());
}
队列满了再添加会一直等待,队列空了再删除会一直等待
4.超时等待
public static void test4() throws InterruptedException {
ArrayBlockingQueue blockingQueue=new ArrayBlockingQueue<>(3);
blockingQueue.offer("a");
blockingQueue.offer("b");
blockingQueue.offer("c");
blockingQueue.offer("d",2,TimeUnit.SECONDS);
//blockingQueue.put("d");//队列没有位置了
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
}
}
添加或删除时,超过限定时间,则退出。