Java 环形队列_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java 环形队列

Java 环形队列

 2017/8/25 19:08:48  luochaobin  程序员俱乐部  我要评论(0)
  • 摘要:publicclassCircleQueue<T>{ReentrantLockreentrantLock=newReentrantLock();privateintcapacity=5;privateintcurrent=0;privateLinkedBlockingQueue<T>[]array=newLinkedBlockingQueue[capacity];publicCircleQueue(){}publicCircleQueue(intcapacity)
  • 标签:Java 队列
class="java keyword" style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace !important; border-radius: 0px !important; background: none !important; border: 0px !important; float: none !important; height: auto !important; line-height: 20px !important; margin: 0px !important; overflow: visible !important; padding: 0px !important; vertical-align: baseline !important; width: auto !important; font-weight: bold !important; font-size: 14px !important; color: #336699 !important;">public?class?CircleQueue<T> { ????ReentrantLock reentrantLock =?new?ReentrantLock(); ? ????private?int?capacity =?5; ? ????private?int?current =?0; ? ????private?LinkedBlockingQueue<T>[] array =?new?LinkedBlockingQueue[capacity]; ? ????public?CircleQueue(){ ? ????} ? ????public?CircleQueue(int?capacity){ ????????this.capacity = capacity; ????} ????public?void?addData(T t) { ????????reentrantLock.lock(); ????????LinkedBlockingQueue<T> clircleData =?null; ????????clircleData = array[(current + capacity -?1) % capacity]; ????????if(null?== clircleData){ ????????????clircleData =?new?LinkedBlockingQueue<>(); ????????????array[(current + capacity -?1) % capacity] = clircleData; ????????} ????????clircleData.add(t); ????????reentrantLock.unlock(); ????} ? ????public?LinkedBlockingQueue<T> getData() { ????????reentrantLock.lock(); ????????LinkedBlockingQueue<T> clircleData = array[current++%capacity]; ????????reentrantLock.unlock(); ????????return?clircleData; ????} ? ????public?static?void?main(String[] args) { ????????CircleQueue circleQueue =?new?CircleQueue(); ????????circleQueue.addData("王伟"); ????????Timer timer =?new?Timer(false); ????????timer.schedule(new?TimerTask() { ????????????@Override ????????????public?void?run() { ????????????????LinkedBlockingQueue queue = circleQueue.getData(); ????????????????if(null?!= queue){ ????????????????????System.out.println(queue.poll()); ????????????????}else{ ????????????????????System.out.println(queue); ????????????????} ? ????????????} ????????},?1000,?1000); ????} }

?

发表评论
用户名: 匿名