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();
}
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;