zoukankan      html  css  js  c++  java
  • BlockingQueue之---ArrayBlockingQueue

    1、直接上代码,注释已经很详细:

      自己拿走试验就行

    /**
    * ArrayBlockingQueue:以数组形式保存数据的阻塞式的有界队列
    * 1、不可扩容--有界
    */
    public class Q_ArrayBlockingQueue {

    //容量为5的队列,不可扩容,最多只能装5个
    private static BlockingQueue<String> strQueue = new ArrayBlockingQueue<String>(5);

    public static void main(String[] args) {

    //先把队列填满,测试其方法
    for (int i = 0; i < 5; i++) {
    //add():添加,有返回值:boolean类型
    strQueue.add("str: " + i);
    }

    //1:add()方法:有boolean类型返回值,添加成功true;失败:报错。
    // boolean addResult = strQueue.add("str:add");
    // System.out.println(addResult);

    //2:offer():boolean类型返回值,成功true;失败false
    // boolean offerResult = strQueue.offer("str: offer");
    //2.1:还可以增加等待时间,超时报错
    // boolean offerResult = false;
    // try {
    // offerResult = strQueue.offer("str: offer", 2, TimeUnit.SECONDS);
    // } catch (InterruptedException e) {
    // System.out.println(e.fillInStackTrace());
    // }

    // //3:put():阻塞方法,如果没有位置了,阻塞等到有位置位置,与take()天生一对
    // try {
    // strQueue.put("str: put");
    // } catch (InterruptedException e) {
    // System.out.println(e.fillInStackTrace());
    // }

    //4:take()方法:目标是第一个元素,阻塞到拿到为止,必须得拿到,性格强势
    // try {
    // String takeResult = strQueue.take();
    // System.out.println(takeResult);
    // } catch (InterruptedException e) {
    // System.out.println(e.fillInStackTrace());
    // }

    //5:poll()比take()温柔多了,等你一段时间,拿不到的话就是null,不等了
    String pollResult = strQueue.poll();
    System.out.println(pollResult);

    }

    }
  • 相关阅读:
    50个好用的前端框架,千万收好以留备用!
    嫦娥五号顺利升空,NASA、欧洲航天局回应
    【电脑故障排查】第1章 BIOS和主板故障
    我的老博客——我在chinaunix的家
    Linux操作系统(第二版)(RHEL 8/CentOS 8)
    Java Web整合开发(21) -- 宏观把握Hibernate
    3 远程仓库
    PHP设计模式-策略模式 转
    ubuntu server设置时区和更新时间
    ubuntu 重启 nginx 失败,* Restarting nginx nginx ...fail!
  • 原文地址:https://www.cnblogs.com/tengri-fighting/p/12787407.html
Copyright © 2011-2022 走看看