在循环中创建新线程

我试图理解为什么这段代码不起作用。

private static object _lock; public static void Main (string[] args) { Thread thread; _lock = new object(); foreach (int num in Enumerable.Range(0,5)) { thread = new Thread (() => print(num.ToString())); thread.Start(); } } public static void print(string text) { lock(_lock) { Console.WriteLine(text); } } 

我最终输出了

4 1 4 4 3

或任何其他随机数字的数字。 为什么重复数字?

因为每个线程都引用了循环变量,并且在创建线程时没有获得自己的副本。

请注意,编译器警告您:“ 访问已修改的闭包 ”。

  foreach (int num in Enumerable.Range(0,5)) { int loopnum = num; thread = new Thread(() => print(loopnum.ToString())); thread.Start(); } 

你的锁根本不做任何事情; 只有一个线程锁定该对象 – 即启动其他对象的线程。 那些其他线程根本不会争夺那个锁。