標籤:console art monitor 用法 write logs 使用 不能 狀態
線程間協作還可通過lock(加鎖)方式進行,lock屬於C#的Monitor文法糖(Monitor後續講解)。使用簡單快捷,如下:
/// <summary> /// 多線程協作-lock捷徑 /// 成功解決多線程對單一資源的共用 /// </summary> private static void MultiThreadSynergicWithLock() { int[] array = new int[3]; Thread producer = new Thread(() => { int count = 0; Random random = new Random(); while (true) { if (10 == count) break; lock (array) { array[0] = random.Next(10); array[1] = random.Next(10); array[2] = random.Next(10); count++; Console.WriteLine(String.Format("{0} work count:{1}。{2}-{3}-{4}", Thread.CurrentThread.Name, count, array[0], array[1], array[2])); } Thread.Sleep(100); } }) { Name = "producer" }; Thread customer = new Thread(() => { //Console.WriteLine(String.Format("{0} start work", Thread.CurrentThread.Name)); int count = 0; while (true) { if (10 == count) break; lock (array) { count++; Console.WriteLine(String.Format("{0} work count:{1}。{2}-{3}-{4}", Thread.CurrentThread.Name, count, array[0], array[1], array[2])); array[0] = 0; array[1] = 0; array[2] = 0; } Thread.Sleep(10); } }) { Name = "customer" }; producer.Start(); customer.Start(); }
說明:
1、通過lock成功解決了多個線程對同一資源的共用使用問題,確保一個線程在lock到資源後,另外需要資源的線程只能處於等待狀態。
2、lock並不能解決線程間順序執行的問題(線程順序執行是指:要求線程A,B滿足,A先執行,B再執行,A又執行,B再次執行這種交替模式)
C#多線程的用法4-線程間的協作lock捷徑