private static Mutex m = new Mutex(); static bool p = true; public static void A() { while (true) { m.WaitOne(); p = !p; Thread.Sleep(5000); Console.WriteLine(Thread.CurrentThread.Name); m.ReleaseMutex(); } } public static void B() { while (true) { m.WaitOne(); //Thread.Sleep(500); Console.WriteLine(Thread.CurrentThread.Name); Console.WriteLine(p); m.ReleaseMutex(); } }
个人体会:
mutex的加锁和解锁和monitor或者lock有些区别,多了通知功能。
不会因为一个线程运行快,而抢了运行慢线程的资源。
相当于,既通知了其他线程,又阻止了当前线程,防止当前线程又抢到资源。
Monitor.Pulse(locker);
Monitor.Wait(locker);