JUC并发编程BlockingQueue(十)

 阻塞队列

JUC并发编程BlockingQueue(十)_第1张图片

 添加移除

四组API

方式 抛出异常 有返回值不抛出异常 阻塞 等待 超时等待
添加 add() offer() put() offer( , , )
移除 remove() poll() take() poll( , )
判断队首元素 element() peek()    

 

 

 

 

 

抛出异常

//抛出异常
    public static  void test1(){
        //队列的大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        System.out.println(blockingQueue.add("a"));//true
        System.out.println(blockingQueue.add("b"));//true
        System.out.println(blockingQueue.add("C"));//true

        System.out.println(blockingQueue.element());//查看队首元素
        System.out.println("-----------------------");
        //java.lang.IllegalStateException Queue full 抛出异常
//        System.out.println(blockingQueue.add("d"));
        System.out.println(blockingQueue.remove());//a
        System.out.println(blockingQueue.element());//查看队首元素
        System.out.println(blockingQueue.remove());//b
        System.out.println(blockingQueue.remove());//c

        //java.util.NoSuchElementException
//        System.out.println(blockingQueue.remove());

    } 
  

 

有返回值不抛出异常

//有返回值不抛出异常
    public static void test2(){
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        System.out.println(blockingQueue.offer("a"));//true
        System.out.println(blockingQueue.offer("b"));//true
        System.out.println(blockingQueue.offer("c"));//true

        System.out.println(blockingQueue.peek());//查看队首元素

        System.out.println(blockingQueue.offer("d"));//false 不抛出异常
        System.out.println("==============");
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());//null 不抛出异常

    } 
  

 

阻塞 等待

//阻塞等待
    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());//没有这个元素 一直阻塞
    } 
  

超时等待

//超时等待
    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);//等待超过2秒就退出

        System.out.println("==================");
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println( blockingQueue.poll(2,TimeUnit.SECONDS));;//等待超过2秒就退出

 
  

 

 

你可能感兴趣的:(JUC并发编程(Java))