我有以下代码创建10个线程,然后将消息写入控制台:
for (int i = 0; i < 10; i++)
{
{
Thread thread = new Thread((threadNumber) =>
{
for (int j = 0; j < 10; j++)
{
Thread.Sleep(200);
Console.WriteLine(string.Format("Thread: {0}, Line: {1}", threadNumber, j));
}
});
thread.Start(i);
}
}
Run Code Online (Sandbox Code Playgroud)
我的理解是ParameterizedThreadStart将一个引用副本的对象发送到该线程.如果是这种情况,因为我没有i在每个循环中创建一个本地副本,所有新线程将指向相同的内存位置,这意味着某些线程号可能被"遗漏".虽然运行了这个(甚至对更多的线程/休眠时间),每个值i都有自己的线程.有谁能解释为什么?