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

Wil*_*iam 1 c# concurrency multithreading

看这里:

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

    new Thread(() => p.SayHello("Thread One")).Start();
    new Thread(() => p.SayHello("Thread Two")).Start();
}
Run Code Online (Sandbox Code Playgroud)

然后:

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

        while (i < 50)
        {
            Console.WriteLine("Hello from " + data);
            i++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么第二个线程没有将变量重置i为0?搞乱它在第一个线程上运行的while循环?

Cod*_*man 5

这是因为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++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Bri*_*sen 5

i是一个局部变量,因此每个线程都有自己的副本i.