理解c#的多线程的时间片分配

xiaoxiao2021-02-28  94

class ThreadClass {         public static void MyThread() {             for (int x = 0; x < 100; x++) {                 Console.ForegroundColor = ConsoleColor.Red;                 Console.Write(x.ToString("000")+" ");             }         }         static void Main(string[] args) {             Thread thrd1 = new Thread(new ThreadStart(MyThread));             thrd1.Start();             for (int x = 300; x < 400; x++) {                 Console.ForegroundColor = ConsoleColor.Green;                 Console.Write((x).ToString("000")+" " );             }             Console.ReadLine();         }

    }

运行,结果如下图:

为什么“000”会显示为绿色?共有两个线程,先运行main中的Console.ForegroundColor = ConsoleColor.Green;和Console.ForegroundColor = ConsoleColor.Green;,显示绿色300->运行MyThread中的Console.ForegroundColor = ConsoleColor.Red->执行main的Console.ForegroundColor->Mythread中的Console.Write(x.ToString("000")+" ");显示绿色000。

同理,“303”、“310”、“312”等显示为红色,而“”003“、”004“、”005“等显示为绿色。

可见多线程的时间片的分配具有很大的不确定性,线程间一般不应共享同一个变量。

Console.ForegroundColor = ConsoleColor.Red;

转载请注明原文地址: https://www.6miu.com/read-51587.html

最新回复(0)