在我下面的代码中, 的Id
属性ThreadClass
未按预期确定性设置(ThreadArray[0]'s ThreadClass.Id = 0, ThreadArray[1]'s ThreadClass.Id = 1,
等)。
如果我调试并放慢速度Thread.Start()'s
,一切都会按预期工作。但是当程序全速运行时,我得到了所有Id's = 4
(或类似的)。我无法锁定i
,因为它不是参考变量。显然,我遇到了竞争条件。我究竟做错了什么?
主文件
for (int i = 0; i < ThreadCount; i++)
{
ThreadArray[i] = new Thread(() =>
{
new ThreadClass(i);
});
ThreadArray[i].Start();
}
线程类.cs
private int Id { get; set; }
public ThreadClass(int i) {
Id = id;
while(true)
{
Console.WriteLine("I am thread " + i");
Thread.Sleep(5000);
}
}
预期输出:
I am thread 0
I am thread 1
I am thread 2
I am thread 3
... 5 second wait ...
I am thread 0
I am thread 1
I am thread 2
I am thread 3
实际输出:
I am thread 4
I am thread 4
I am thread 4
I am thread 4
... 5 second wait ...
I am thread 4
I am thread 4
I am thread 4
I am thread 4
请注意,此时每个实例都ThreadArray
被初始化为一个有效Thread
对象。