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

时间:2013-10-15 21:25:39

标签: c# multithreading concurrency

看这里:

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

3 个答案:

答案 0 :(得分: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++;
        }
    }
}

答案 1 :(得分:5)

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

答案 2 :(得分:0)

将它想象成每个线程使用它的局部变量获得它自己的SayHello方法的“副本”。如果你想要两个线程都使用相同的i,你必须通过引用传递它,然后开始有趣。