java 多线程-6(阻塞队列BlockingQueue)

BlockingQueue

1、简介

BlockingKQueue,阻塞队列。是一个队列,在多线程情况下,当需要入队而队列已满或需要出队而队列为空时,会造成阻塞,即线程挂起,一但入队或出队的条件满足,线程又自动唤醒。在消费者生产者问题中,可通过阻塞队列传递数据,当生产者消费者数据处理速度不一致时,例如,生产者速度大于消费者,当生产者的数据积累到一定程度时,就阻塞生产者线程,反之亦然。

2、BlockingKQueue的四组API

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

代码示例:通过构造BlockingQueue的实现类ArrayBlockingQueue的对象来测试

第一组
public static void test1(){
        BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue(2);
        blockingQueue.add(1);
        blockingQueue.add(2);
        //blockingQueue.add(3); //超过队列大小,报IllegalStateException异常
        System.out.println(blockingQueue.element());//查看队首元素
        System.out.println("======================");
        blockingQueue.remove();
        blockingQueue.remove();
        //blockingQueue.remove();// 移除不存在的元素,报NoSuchElementException异常
    }
第二组
public static void test2(){
        BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue(2);
        blockingQueue.offer(1);
        blockingQueue.offer(2);
        //blockingQueue.offer(3);//不报错,返回false
        System.out.println(blockingQueue.peek());//查看队首元素
        System.out.println("======================");
        blockingQueue.poll();
        blockingQueue.poll();
        //blockingQueue.poll();//不报错,返回null
    }
第三组
public static void test3() throws InterruptedException {
        BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue(2);
        blockingQueue.put(1);
        blockingQueue.put(2);
        //blockingQueue.put(3);// 一直阻塞
        System.out.println("======================");
        blockingQueue.take();
        blockingQueue.take();
        //blockingQueue.take();// 一直阻塞
    }
第四组
 public static void test4() throws InterruptedException {
        BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue(2);
        blockingQueue.offer(1);
        blockingQueue.offer(2);
        //blockingQueue.offer(3,2, TimeUnit.SECONDS);//队列已满,等待2秒后退出
        System.out.println("======================");
        blockingQueue.poll();
        blockingQueue.poll();
        blockingQueue.poll(2, TimeUnit.SECONDS);//队列已空,等待2秒后退出
    }

3、BlockingQueue的常用实现类

1、ArrayBlockingQueue

由数组结构组成的有界阻塞队列,容量是有限的,必须初始化容量。

2、LinkedBlockingQueue

由链表结构组成的无界阻塞队列,容量有限,默认容量为Integer.MAX_VALUE

3、PriorityBlockingQueue

支持优先级的无界阻塞队列

4、DelayQueue

使用优先级队列实现的无界阻塞队列

5、SynchronousQueue

不存储元素的阻塞队列

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值