/// <summary> /// 使用C#的lock关键字 /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine("Incorrect counter"); var c = new Counter(); var t1 = new Thread(() => TestCounter(c)); var t2 = new Thread(() => TestCounter(c)); var t3 = new Thread(() => TestCounter(c)); t1.Start(); t2.Start(); t3.Start(); t1.Join(); t2.Join(); t3.Join(); // 多个线程中存在竞争条件(race condition) // 由于++并不是一个线程安全的操作,所以输出结果一般都不为0 Console.WriteLine($"Total count: {c.Count}"); Console.WriteLine("----------------------------------------"); Console.WriteLine("Correct counter"); var c1 = new CounterWithLock(); t1 = new Thread(() => TestCounter(c1)); t2 = new Thread(() => TestCounter(c1)); t3 = new Thread(() => TestCounter(c1)); t1.Start(); t2.Start(); t3.Start(); t1.Join(); t2.Join(); t3.Join(); Console.WriteLine($"Total count: {c1.Count}"); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("Incorrect counter"); var c = new Counter(); var t1 = new Thread(() => TestCount(c)); var t2 = new Thread(() => TestCount(c)); var t3 = new Thread(() => TestCount(c)); t1.Start(); t2.Start(); t3.Start(); t1.Join(); t2.Join(); t3.Join(); Console.WriteLine($"Total count: {c.Count}"); Console.WriteLine("-----------------------"); Console.WriteLine("Correct counter"); var c1 = new CounterWithLock(); t1 = new Thread(() => TestCount(c1)); t2 = new Thread(() => TestCount(c1)); t3 = new Thread(() => TestCount(c1)); t1.Start(); t2.Start(); t3.Start(); t1.Join(); t2.Join(); t3.Join(); Console.WriteLine($"Total count: {c1.Count}"); }