阻塞队列BlockingQueue一 增删取api

ArrayBlockingQueue需要初始化长度的阻塞队列 先进先出
* 添加元素用add方法时,如果超过定义的长度则会抛出异常 java.lang.IllegalStateException: Queue full
* 取出元素时用remove方法,如果删除的元素超出定义长度则抛出异常 java.util.NoSuchElementException
* element 方法始终取到队列第一个元素
*
* 添加元素offer方法,当添加的元素超出定义的队列长度时,返回false不插入,不会报错
* peek 方法始终取到队列第一个元素
* 取出删除元素poll方法,当取出元素次数大于队列长度时返回null,不会报错
*
* 添加元素put方法,如果队列已满,则会阻塞。直到队列有空位插入为止
* 取出删除元素take方法,如果队列已空,则会一直阻塞,直到队列有元素可以消费
*
* 阻塞添加元素offer(元素,时间数,时间单位) 当添加元素大于队列长度时,等待定义的单位时间数,如果队列还是慢的则返回false
* 阻塞取出元素poll(时间数,时间单位) 当队列没有元素时,等待定义的单位时间数,如果还没有可取元素则返回null

 

public class BlockingQueueDemo1 {
    public static void main(String[] args) throws InterruptedException {
        
        BlockingQueue<String> bq = new ArrayBlockingQueue<>(3);
        System.out.println(bq.add("a"));
        System.out.println(bq.add("b"));
        System.out.println(bq.add("c"));
        
        //System.out.println(bq.add("d"));
        
        System.out.println(bq.element());
        System.out.println(bq.element());
        System.out.println(bq.element());
        
        
        System.out.println(bq.remove());
        System.out.println(bq.remove());
        System.out.println(bq.remove());
        //System.out.println(bq.remove());
        
        
        System.out.println("++++++++++++++");
        System.out.println(bq.offer("d"));
        System.out.println(bq.offer("e"));
        System.out.println(bq.offer("f"));
        System.out.println(bq.offer("g"));
        
        System.out.println(bq.peek());
        System.out.println(bq.peek());
        System.out.println(bq.peek());
        
        System.out.println(bq.poll());
        System.out.println(bq.poll());
        System.out.println(bq.poll());
        System.out.println(bq.poll());
        
        
        System.out.println("============================");
        bq.put("h");
        bq.put("i");
        bq.put("j");
        //bq.put("k");
        System.out.println("生产-----消费");
        System.out.println(bq.take());
        System.out.println(bq.take());
        System.out.println(bq.take());
        //System.out.println(bq.take());
        
        System.out.println("++++++++++++++++++++");
        System.out.println(bq.offer("l", 2, TimeUnit.SECONDS));
        System.out.println(bq.offer("m", 2, TimeUnit.SECONDS));
        System.out.println(bq.offer("n", 2, TimeUnit.SECONDS));
        //System.out.println(bq.offer("o", 2, TimeUnit.SECONDS));
        
        System.out.println(bq.poll(2, TimeUnit.SECONDS));
        System.out.println(bq.poll(2, TimeUnit.SECONDS));
        System.out.println(bq.poll(2, TimeUnit.SECONDS));
        System.out.println(bq.poll(2, TimeUnit.SECONDS));
        
        
    }

}

 

posted @ 2019-05-13 00:53  fuguang  阅读(844)  评论(0编辑  收藏  举报