阻塞队列

 阻塞队列特性:FIFO  先进先出  first input first output

在多线程并发处理,线程池中我们会使用到阻塞队列。

不得不阻塞:

写入:如果队列满了,就必须阻塞等待

取出:当队列是空的,那就必须阻塞等待生产

BlockingQueye : 阻塞队列

Deque : 双端队列

AbstractQueue : 非阻塞队列

 

 

 

查看队首元素:blockingQueue.element();

 

四组API:

 

 

public class testBqq {
public static void main(String[] args) throws InterruptedException {
System.out.println("hello world");
test5();
}
/*
抛出异常
*/
public static void test1(){
//队列大小
ArrayBlockingQueue bq = new ArrayBlockingQueue<>(3);
System.out.println(bq.add("a"));
System.out.println(bq.add("b"));
System.out.println(bq.add("c"));
//IllegalStateException: Queue full
//System.out.println(bq.add("d"));
System.out.println(bq.remove());
System.out.println(bq.remove());
System.out.println(bq.remove());
//NoSuchElementException
System.out.println(bq.remove());
}
/*
不抛出异常
*/
public static void test2(){
ArrayBlockingQueue bqueue = new ArrayBlockingQueue<>(3);
System.out.println(bqueue.offer("a"));
System.out.println(bqueue.offer("b"));
System.out.println(bqueue.offer("c"));
//溢出部分返回false
System.out.println(bqueue.offer("d"));
System.out.println(bqueue.poll());
System.out.println(bqueue.poll());
System.out.println(bqueue.poll());
//取空之后返回null
System.out.println(bqueue.poll());
}
public static void test3(){
ArrayBlockingQueue bqq = new ArrayBlockingQueue<>(3);
System.out.println(bqq.add("a"));
System.out.println(bqq.add("b"));
System.out.println(bqq.add("c"));
System.out.println(bqq.offer("d"));//没有位置 就返回false
//不抛出异常情况下的查看队首
System.out.println(bqq.peek());
System.out.println(bqq.remove());
//查看队首
System.out.println(bqq.element());
System.out.println(bqq.remove());
System.out.println(bqq.remove());
System.out.println(bqq.poll());//移除 不抛出异常 没有值返回null
}
/*
等待,阻塞 一直阻塞
*/
public static void test4() throws InterruptedException {
//队列的大小
ArrayBlockingQueue bqq = new ArrayBlockingQueue<>(3);
bqq.put("a");
bqq.put("b");
bqq.put("c");
//bqq.put("d");//队列没有位置了,一直阻塞

System.out.println(bqq.take());
System.out.println(bqq.take());
System.out.println(bqq.take());
//System.out.println(bqq.take());//队列没有位置了,一直阻塞等待
}
/*
超时,退出
*/
public static void test5() throws InterruptedException {
ArrayBlockingQueue bqq = new ArrayBlockingQueue<>(3);
bqq.offer("a");
bqq.offer("b");
bqq.offer("c");
bqq.offer("d",2, TimeUnit.SECONDS);//等待超时两秒就退出
System.out.println(bqq.poll());
System.out.println(bqq.poll());
System.out.println(bqq.poll());
System.out.println(bqq.poll(2, TimeUnit.SECONDS));//超过两秒就退出 放弃
}
}

 

 

 

 

同步队列:

没有容量,不用设置容量,最多存储一个元素。

存储一个元素,必须等待取出之后才能在放。  put  take

和其他的BlockingQueue不一样   SynchronousQueue不存储元素

put了一个元素,必须从里面先take取出来,否则不能out进去值

 

posted @ 2020-05-27 19:11  SpaceJz  阅读(240)  评论(0编辑  收藏  举报