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
);
????
}
}
?