生产者消费者demo
using System; using System.Collections.Generic; using System.Threading; namespace 生产者消费者 { class Program { static int r; static Queue<int> q = new Queue<int>(); static Object obj; static int c = 0; static void Main(string[] args) { obj = new Object(); var _worker = new Thread(生产); _worker.Start(); //var _worker2 = new Thread(生产); //_worker2.Start(); var 消费者1 = new Thread(消费者); 消费者1.Start(); var 消费者2 = new Thread(消费者); 消费者2.Start(); var 消费者3 = new Thread(消费者); 消费者3.Start(); var 消费者4 = new Thread(消费者); 消费者4.Start(); var 消费者5 = new Thread(消费者); 消费者5.Start(); Console.ReadKey(); Console.WriteLine("f:" + c); Console.ReadKey(); } private static void 消费者() { while (true) { bool stat = false; lock (obj) { stat = q.TryDequeue(out r); if (stat) { c++; Console.WriteLine(q.Count+":"+r); } } if (stat == false) { Thread.Sleep(100); } } } private static void 生产() { for (int i = 1; i <= 10000 / 2; i++) { lock (obj) { q.Enqueue(i); } } } } }