給一個很有趣的進程並發性的小例子:
static void Main(string[] args) { new Thread(WriteX).Start(); new Thread(WriteY ).Start(); WriteZ(); Console.ReadKey(); } static void WriteX() { Console.WriteLine($"線程編號X:{Thread.CurrentThread.ManagedThreadId}"); for (int i = 0; i < 1000; i++) Console.Write("x"); } static void WriteY() { Console.WriteLine($"線程編號Y:{Thread.CurrentThread.ManagedThreadId}"); for (int i = 0; i < 1000; i++) Console.Write("y"); } static void WriteZ() { Console.WriteLine($"線程編號Z:{Thread.CurrentThread.ManagedThreadId}"); for (int i = 0; i < 1000; i++) Console.Write("z"); } }
一共開了三個進程,分別打印X, Y,Z,看運行結果(每次都是隨機的)