多線程, 當使用共有變量時, 保持計算結果正確很重要:多線程
看下面的例子:spa
private static int count = 10; //private static object objlock = new object(); public static void Main(string[] args) { try { for (int i = 0; i < 20; i++) { Thread t1 = new Thread(new ThreadStart(WriteNumber)); t1.Name = "Name-" + i.ToString(); t1.Start(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } public static void WriteNumber() { //lock (objlock) //{ count--; Thread.Sleep(1000); Console.WriteLine("Name:" + Thread.CurrentThread.Name + " count:" + count.ToString()); //} }
結果這樣,全錯了。線程
加上lock以後, 代碼修改成這樣code
private static int count = 10; private static object objlock = new object(); public static void Main(string[] args) { try { for (int i = 0; i < 20; i++) { Thread t1 = new Thread(new ThreadStart(WriteNumber)); t1.Name = "Name-" + i.ToString(); t1.Start(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } public static void WriteNumber() { lock (objlock) { count--; Thread.Sleep(1000); Console.WriteLine("Name:" + Thread.CurrentThread.Name + " count:" + count.ToString()); } }
運行結果是這樣:blog
注意:private static object objlock = new object(); //定義這個變量的位置,string
各線程運行前後, 由CPU隨機執行, 每次運行均可能看到不一樣的前後順序。it