class Test { public static Queue<int> queue = new Queue<int>(10000); Thread putIntThread; Thread takeIntThread; public Test() { for(int i = 0; i < 5000; ++i) { queue.Enqueue(0); } putIntThread = new Thread(this.PutInt); takeIntThread = new Thread(this.TakeInt); putIntThread.Start(); takeIntThread.Start(); } void PutInt() { while(true) { if(queue.Count < 10000) {//no need to lock here as only itself can change this condition queue.Enqueue(0); } } } void TakeInt() { while(true) { if(queue.Count > 0) {//no need to lock here as only itself can change this condition queue.Dequeue(); } } } }
编辑:我必须使用.NET 3.5
解决方法
Queue<T>
的文件.
Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
A
Queue<T>
can support multiple readers concurrently,as long as the collection is not modified. Even so,enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration,you can lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing,you must implement your own synchronization.
重读你的问题,你似乎对这个短语“这种类型的静态成员”感到困惑 – 这不是说“静态队列”,因为没有这样的事情.一个对象不是静态的 – 一个成员是.当谈到静态成员时,它谈论的是Encoding.GetEncoding(Queue< T>实际上没有任何静态成员).实例成员是Enqueue和Dequeue – 与类型实例相关的成员,而不是类型本身.
因此,您需要为每个操作使用锁定,或者如果您使用的是.NET 4,请使用ConcurrentQueue<T>
.