C#经典面试题:
有3个线程,A线程打印1,B线程打印2,C线程打印3,请用程序实现依次打印123123123...
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 var mt = new MyThread(); 6 mt.Run(); 7 8 Console.ReadLine(); 9 } 10 } 11 12 13 internal class MyThread 14 { 15 private int number = 0; 16 object obj = new object(); 17 18 public void Run() 19 { 20 var ta = new Thread(PrintNumber); 21 var tb = new Thread(PrintNumber); 22 var tc = new Thread(PrintNumber); 23 24 ta.Start("1"); 25 tb.Start("2"); 26 tc.Start("3"); 27 } 28 29 private void PrintNumber(object num) 30 { 31 for (int i = 0; i < 9; i++) 32 { 33 lock (obj) 34 { 35 if (Convert.ToInt32(num) == number + 1 || Convert.ToInt32(num) == number - 2) 36 { 37 Console.Write(num); 38 number = Convert.ToInt32(num); 39 40 // 通知正在等候的线程 41 Monitor.PulseAll(obj); 42 } 43 else 44 { 45 // 本轮不应该打印的线程,就让他到lock外面等候通知 46 // 因为本次他也执行了判断,所以循环就少了一次 47 i--; 48 Monitor.Wait(obj); 49 } 50 } 51 } 52 } 53 }
偷 @宋兴柱-Sindrol 同学的代码:C#中添加三个线程同时启动执行某一方法,并依次调用某方法中的循环打印输