我有这段代码:
Thread[] threadsArray = new Thread[4];
for (int i = 0; i < 4; i++)
{
threadsArray[i] = new Thread(() => c1.k(i));
}
for (int i = 0; i < 4; i++)
{
threadsArray[i].Start();
}
for (int i = 0; i < 4; i++)
{
threadsArray[i].Join();
}
函数k是这样的:
void k(int i)
{
while(true)
Console.WriteLine(i);
}
由于某种原因,最后一个线程正在运行并打印4444444 .... 为什么不是所有的线程都在运行?
答案 0 :(得分:24)
所有线程都在打印相同的变量。
您的lambda表达式(() => c1.k(i)
)通过引用捕获i
变量
因此,当lambda表达式在i++
之后运行时,它会获取i
的新值。
要解决这个问题,你需要在循环中声明一个单独的变量,以便每个lambda获得自己的变量,如下所示:
for (int i = 0; i < 4; i++)
{
int localNum = i;
threadsArray[i] = new Thread(() => c1.k(localNum));
}
答案 1 :(得分:4)
你正在关闭i变量。
试试这个
for (int i = 0; i < 4; i++)
{
int x = i;
threadsArray[i] = new Thread(() => c1.k(x));
}
答案 2 :(得分:0)
Thread[] threadsArray = new Thread[4];
for (int i = 0; i < 4; i++)
{
//better use ParameterizedThreadStart Delegate
threadsArray[i] = new Thread(k);
}
for (int i = 0; i < 4; i++)
{
//passing the value to the function
threadsArray[i].Start(i);
}
for (int i = 0; i < 4; i++)
{
threadsArray[i].Join();
}
//changing the input data type
void k(object i)
{
while (true)
Console.WriteLine((int)i);
}