zoukankan      html  css  js  c++  java
  • reentrantlocklock实现有界队列

    今天找synchronize和reentrantlock区别的时候,发现有个使用reentrantlock中的condition实现有界队列,感觉挺有趣的,自己顺手敲了一遍

    class Queue{
        private Object[]queue;
        private int size;       //记录队列的大小这样你就不需要累次调用queue.length
        private int length=0;   //用于记录队列中元素的个数
        private int addindex=0;
        private int rmindex=0;
        private Lock lock= new ReentrantLock();
        private Condition full =lock.newCondition();
        private Condition empty =lock.newCondition();
        
    
        public Queue(int size) {
            this.size=size;
            queue=new Object[size];
        }
        public void add(Object object) throws InterruptedException {
            lock.lock();
            try {
                if(length==size) {
                    System.out.println("queue already full");
                    full.await();
                }
                queue[addindex]=object;
                length++;
                if(++addindex == size)
                    addindex=0;
                empty.signalAll();        
            } finally {
                lock.unlock();// TODO: handle finally clause
            }    
        }
        public Object remove()throws InterruptedException {
            lock.lock();
            try {
                if(length==0) {
                    System.out.println("there was nothing to remove");
                    empty.await();
                }
                Object object=queue[rmindex];
                length--;
                if(++rmindex==size)
                    rmindex=0;
                full.signalAll();
                return object;
            } finally {
                lock.unlock();
            }
        }
    }
  • 相关阅读:
    安装 android sdk 时,dl.google.com 连不上各种尝试
    解决android SDK 安装过程中 packages 列表为空的问题
    Java 集合 -- Deque
    Java 集合 -- Queue
    Java 集合 -- Set
    Java 集合 -- Map
    Java 集合 -- List
    Java 语言进阶 -- 线程
    Java 语言基础知识
    Java 网络编程基础 -- TCP 编程
  • 原文地址:https://www.cnblogs.com/feixiangdecainiao/p/10443789.html
Copyright © 2011-2022 走看看