| | |
| | | |
| | | public NewsQueue(Class<T> cls, int capacity) { |
| | | this.cls = cls; |
| | | arr = (T[]) Array.newInstance(cls, capacity); |
| | | this.arr = (T[]) Array.newInstance(cls, capacity); |
| | | this.capacity = capacity; |
| | | } |
| | | |
| | | public synchronized boolean offer(T t) { |
| | | if (this.tail == this.capacity) { |
| | | this.peek(); |
| | | } |
| | | this.reform(); |
| | | this.arr[this.tail] = t; |
| | | this.tail ++; |
| | | return true; |
| | | } |
| | | |
| | | public synchronized boolean put(T t) { |
| | | if (this.tail == this.capacity) { |
| | | return false; |
| | | } else { |
| | | for (int i = this.head; i < this.tail; i++) { |
| | | this.arr[i-this.head] = this.arr[i]; |
| | | } |
| | | this.tail -= this.head; |
| | | this.head = 0; |
| | | this.reform(); |
| | | } |
| | | this.arr[this.tail] = t; |
| | | this.tail ++; |
| | |
| | | } |
| | | T t = this.arr[this.head]; |
| | | this.head ++; |
| | | this.reform(); |
| | | return t; |
| | | } |
| | | |
| | | private void reform() { |
| | | for (int i = this.head; i < this.tail; i++) { |
| | | this.arr[i-this.head] = this.arr[i]; |
| | | } |
| | | this.tail -= this.head; |
| | | this.head = 0; |
| | | } |
| | | |
| | | public synchronized int size() { |
| | | return this.tail - this.head; |
| | | } |