using System; using System.Collections.Generic; using System.Text; namespace CommonLib.DataStruct { /// /// 环形缓冲区 /// /// public class RingArray:IDisposable { protected T[] queue; protected int length; protected int m_capacity; protected int head = 0; protected int tail = 0; private Object LockObj = new Object(); public int capacity { get { return m_capacity; } } public RingArray(int capacity) { this.m_capacity = capacity; this.head = 0; this.tail = 0; this.length = 0; this.queue = new T[capacity]; } public void Clear() { lock (LockObj) { head = 0; tail = 0; length = 0; } } public bool IsEmpty() { Boolean bResult = false; lock (LockObj) { bResult = length == 0; } return bResult; } public bool IsFull() { Boolean bResult = false; lock (LockObj) { bResult = length == m_capacity; } return bResult; } public int Length() { lock (LockObj) { return length; } } /// /// 入栈.如果超过,挤掉最前面的一个 /// /// /// public bool EnQueue(T node) { lock (LockObj) { if (IsFull()) { DeQueue(); } //if (!IsFull()){ queue[tail] = node; tail = (++tail) % m_capacity; length++; } return true; //return false;} } public T DeQueue() { T node = default(T); lock (LockObj) { if (!IsEmpty()) { node = queue[head]; head = (++head) % m_capacity; length--; } } return node; } public T PeekData() { T node = default(T); lock (LockObj) { if (!IsEmpty()) { node = queue[head]; } } return node; } public void Traverse() { for (int i = head; i < length + head; i++) { //Console.WriteLine(queue[i % m_capacity]); //Console.WriteLine(string.Format("前面还有{0}个", i - head)); } } public void Dispose() { queue = null; } } }