static void Main(string[] args)
{
test p = new test();
new Thread(() => p.SayHello("Thread One")).Start();
new Thread(() => p.SayHello("Thread Two")).Start();
}
則:
class test
{
public void SayHello(string data)
{
int i = 0;
while (i < 50)
{
Console.WriteLine("Hello from " + data);
i++;
}
}
}
爲什麼第二個線程不會重置變量i
爲0?並弄亂它在第一個線程上運行的while循環?
同步調用這些方法並沒有什麼不同。當一個線程(任何線程)進入方法時,局部變量只能在方法中使用。如果它們被吊起來,那麼它就變成另一個故事了。 –