小编Leo*_*eon的帖子

在循环中创建新线程

我试图理解为什么这段代码不起作用.

    private static object _lock;

    public static void Main (string[] args)
    {
        Thread thread;
        _lock = new object();

        foreach (int num in Enumerable.Range(0,5)) {
            thread  = new Thread (() => print(num.ToString()));
            thread.Start(); 
        }
    }

    public static void print(string text)
    {
        lock(_lock)
        {
            Console.WriteLine(text);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我最终输出了

4 1 4 4 3

或任何其他随机数字的数字.为什么重复数字?

c# multithreading

2
推荐指数
1
解决办法
4843
查看次数

标签 统计

c# ×1

multithreading ×1