-
阻塞队列有四种阻塞方式
1.遇到阻塞就抛出异常
2.遇到阻塞不抛出异常,返回false
3.遇到阻塞就等待,一直等待
4.遇到阻塞就等待,直到等待超时退出
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class test01 {
public static void main(String[] args) throws InterruptedException {
//test1();
//test2();
//test3();
test4();
}
//遇到阻塞就抛出异常
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.add("d"));
System.out.println(blockingQueue.element()); //打印出队首
System.out.println(blockingQueue.remove()); //从队列中移除元素
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//System.out.println(blockingQueue.remove()); //NoSuchElementException
}
//遇到阻塞不抛出异常,返回false
public static void test2(){
ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<