zoukankan      html  css  js  c++  java
  • BlockingQueue

    BlockingQueue 是一个生产者消费者队列,可以很好的实现资源的有序存取,主要有LinkedBlockingQueue和ArrayBlockingQueue两个实现
    主要的方法:

    (一)放入数据

     (1)offer(anObject): 将anObject加到BlockingQueue里,成功返回true,否则返回false.(本方法不阻塞当前执行方法的线程);  
        
    (2)offer(E o, long timeout, TimeUnit unit):可以设定等待的时间,如果在指定的时间内,还不能往队列中加入BlockingQueue,则返回false。

    (二)获取数据

     (1)poll(time):取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回null;

     (2)poll(long timeout, TimeUnit unit):从BlockingQueue取出一个队首的对象,如果在指定时间内,队列一旦有数据可取,则立即返回队列中的数据。否则知道时间

    超时还没有数据可取,返回失败。

     (3)take():取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到BlockingQueue有新的数据被加入;
    (4)drainTo():一次性从BlockingQueue获取所有可用的数据对象(还可以指定获取数据的个数),通过该方法,可以提升获取数据效率;不需要多次分批加锁或释放锁,返回list。

    例如:有两个线程,一个线程每2秒放入一个100以内的整数,另一个线程每10秒按放入的顺序拿出这些整数。

            BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(10);
            ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
            executorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    Random r =new Random();
                    int value = r.nextInt(101);
                    System.out.println("放入元素"+value);
                    blockingQueue.offer(value);
    
                }
            },0,2,TimeUnit.SECONDS);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true){
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        List<Integer> integerList =  Lists.newArrayList();
                        blockingQueue.drainTo(integerList);
                        integerList.forEach(System.out::println);
                    }
                }
            }).start();
    

  • 相关阅读:
    新零售解决方案体系架构
    设计模式-分类
    设计模式-设计原则
    一天一个 Linux 命令(12):tree 命令
    RabbitMQ中如何保证消息的可靠传输?如果消息丢了怎么办
    为什么使用MQ?
    一天一个 Linux 命令(11):cp命令
    数据结构和算法-线性查找-二分查找
    作图工具汇总
    Git 命令大全,Git命令汇总,Git命令说明
  • 原文地址:https://www.cnblogs.com/hts-technology/p/9300427.html
Copyright © 2011-2022 走看看