gpt4 book ai didi

c# - 当线程运行相同的方法时,为什么值不冲突?

转载 作者:太空宇宙 更新时间:2023-11-03 17:41:35 26 4
gpt4 key购买 nike

看这里:

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循环?

最佳答案

这是因为int i是局部变量。如果您使它对类是静态的,而不是局部变量,它将被重置。在这种情况下,变量被隔离到每个线程。

例子:

static void Main(string[] args)
{
test p = new test();

new Thread(() => p.SayHello("Thread One")).Start();
new Thread(() => p.SayHello("Thread Two")).Start();
}

public class test
{
static int i = 0;
public static void SayHello(string data)
{
i = 0;

while (i < 50)
{
Console.WriteLine("Hello from " + data);
i++;
}
}
}

关于c# - 当线程运行相同的方法时,为什么值不冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19391397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com