Skip to content

线程不是立即启动的

🏷️ C# 学习 C#

先看一下下面的代码:

cs
using System;
using System.Threading;

namespace ThreadIsNotStartImmediately
{
    class Program
    {
        static int _id = 0;

        static void Main(string args)
        {
            for (int i = 0; i < 10; i++, _id++)
            {
                Thread t = new Thread(() =>
                {
                    Console.WriteLine(string.Format("{0}:{1}", 
                        Thread.CurrentThread.Name, _id));
                });
                t.Name = string.Format("Thread{0}", i);
                t.IsBackground = true;
                t.Start();
            }
            Console.ReadLine();
        }
    }
}

想定的输出结果是:

Thread0:0
Thread1:1
Thread2:2
Thread3:3
Thread4:4
Thread5:5
Thread6:6
Thread7:7
Thread8:8
Thread9:9

实际的输出结果可能是(每次的执行结果可能都不一样):

Thread0:2
Thread2:3
Thread1:2
Thread5:6
Thread4:4
Thread7:8
Thread6:6
Thread3:3
Thread9:10
Thread8:8

实际的输出结果证明:线程不是立即启动的