C #3 threads a B C print 123123123 in sequence ..,
C # typical interview questions:
There are 3 threads, thread A prints 1, thread B prints 2, and thread C prints 3. Please Print 123123123 in sequence with the program implementation...
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 MyThread14 {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 // notify the waiting thread 41 Monitor. pulseAll (obj); 42} 43 else44 {45 // the thread that should not be printed in this round. Let him wait for the notification to be sent out of lock, therefore, the cycle is reduced by 47 I --; 48 Monitor. wait (obj); 49} 50} 51} 52} 53}
Steal @Song Xingzhu-SindrolCode of students: add three threads in C # to execute a method at the same time, and call the cyclic print input in a method in turn