学习线程,处理共享资源,要保证每个线程对资源是安全的,这里模拟一个吃馍馍的例子,用一个线程作生产者单独生成镆镆,再随机生成几个线程来模拟消费者吃馍馍,生产的馍馍为0后其消费者无法再吃到馍馍,只能等生产者生产馍馍。
static Mutex m = new Mutex(); static void Main(string[] args) { momo = new Momo(); CreateMomo(); for (int j = 0; j < new Random().Next(3); j++) { while (true) { Consume(); Thread.Sleep(1000); } } } static Momo momo = null; static int i = 0; public async static void CreateMomo() { await Task.Run(async () => { while (true) { await Task.Delay(new Random().Next(2000)); m.WaitOne(); //生产Momo momo.list.Add(new Momo(++i)); Console.WriteLine("生产一个MOmo,共有Momo:" + momo.Count); m.ReleaseMutex(); } }); } public async static void Consume() { await Task.Run(async () => { await Task.Delay(new Random().Next(20000)); m.WaitOne(); if (momo.Count <= 0) { Console.WriteLine("无Momo," + Thread.CurrentThread.ManagedThreadId + "没吃着"); m.ReleaseMutex(); return; } momo.list.RemoveAt(0); Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "吃了一个,还剩" + momo.Count); m.ReleaseMutex(); }); }