java 集合之Queue

Queue

先入先出(FIFO)的数据结构

继承关系

在这里插入图片描述
在这里插入图片描述

1、ArrayBlockingQueue

方法对比
方法名作用结果
add增加一个元素如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove移除并返回队列头部的元素如果队列为空,则抛出一个NoSuchElementException异常
element返回队列头部的元素如果队列为空,则抛出一个NoSuchElementException异常
offer添加一个元素并返回true如果队列已满,则返回false
poll移除并返问队列头部的元素如果队列为空,则返回null
peek返回队列头部的元素如果队列为空,则返回null
put添加一个元素如果队列满,则阻塞
take移除并返回队列头部的元素如果队列为空,则阻塞
案例
    public static void main(String[] args) throws InterruptedException {
        Queue queue = new ArrayBlockingQueue<>(3);
        System.out.println(queue.add("tom"));
        System.out.println(queue.add("jack"));
        System.out.println(queue.add("jimi"));
        //超过元素个数报异常
//      System.out.println(queue.add("lingke"));

        System.out.println("queue.element():" + queue.element());

        System.out.println("queue.remove():" + queue.remove());
        System.out.println("queue.remove():" + queue.remove());
        System.out.println("queue.remove():" + queue.remove());
        //超过元素个数报异常
//        System.out.println(queue.remove());


        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));
        //超过元素个数返回false
        System.out.println(blockingQueue.offer("d"));

        System.out.println("blockingQueue.peek():" + blockingQueue.peek());

        System.out.println("blockingQueue.poll():" + blockingQueue.poll());
        System.out.println("blockingQueue.poll():" + blockingQueue.poll());
        System.out.println("blockingQueue.poll():" + blockingQueue.poll());
        //超过元素个数返返回null
        System.out.println("blockingQueue.poll():" + blockingQueue.poll());

        BlockingQueue<String> blockingQueue2 = new ArrayBlockingQueue<>(3);
        blockingQueue2.put("a");
        blockingQueue2.put("b");
        blockingQueue2.put("c");
        //超过元素个数阻塞
//        blockingQueue2.put("d");

        System.out.println(blockingQueue2.take());
        System.out.println(blockingQueue2.take());
        System.out.println(blockingQueue2.take());
        //超过元素个数阻塞
        System.out.println(blockingQueue2.take());
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值