C# 两个线程交替打印0~100的奇偶数
两个线程交替打印0~100的奇偶数
1 using System; 2 using System.Threading; 3 4 namespace Demo.Services 5 { 6 public class ThreadDemo 7 { 8 public ThreadDemo() 9 { 10 } 11 ///<summary> 12 ///两个线程交替打印0~100的奇偶数 13 ///</summary> 14 public static void PrintOddEvenNumber() 15 { 16 var work = new TheadPrintNumWork(); 17 var threadOdd = new Thread(work.PrintOddNumer) { Name = "奇数线程" }; 18 var threadEven = new Thread(work.PrintEvenNumber) { Name = "偶数线程" }; 19 threadOdd.Start(); 20 threadEven.Start(); 21 } 22 23 24 25 } 26 27 public class TheadPrintNumWork 28 { 29 30 private static readonly AutoResetEvent oddAre = new AutoResetEvent(false); 31 32 private static readonly AutoResetEvent evenAre = new AutoResetEvent(false); 33 34 public void PrintOddNumer() 35 { 36 oddAre.WaitOne(); 37 for (var i = 0; i <= 100; i++) 38 { 39 if (i % 2 != 1) continue; 40 Console.WriteLine($"{Thread.CurrentThread.Name}:{i}"); 41 evenAre.Set(); 42 oddAre.WaitOne(); 43 } 44 } 45 46 public void PrintEvenNumber() 47 { 48 for (var i = 0; i <= 100; i++) 49 { 50 if (i % 2 != 0) continue; 51 Console.WriteLine($"{Thread.CurrentThread.Name}:{i}"); 52 oddAre.Set(); 53 evenAre.WaitOne(); 54 } 55 } 56 } 57 }
收余恨、免娇嗔、且自信、改性情,休恋逝水,苦海回身,早悟兰因。