多线程, 当使用共有变量时, 保持计算结果正确很重要:
看下面的例子:
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之后, 代码修改为这样
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()); } }
运行结果是这样:
注意:private static object objlock = new object(); //定义这个变量的位置,
各线程运行先后, 由CPU随机执行, 每次运行都可能看到不同的先后顺序。