C # Classic Interview questions:
There are 3 threads, a thread print 1,b thread print 2,c thread print 3, please use the program implementation to print 123123123 ...
1 class Program2 {3 Static voidMain (string[] args)4 {5 varMT =NewMyThread ();6 Mt. Run ();7 8 console.readline ();9 }Ten } One A - Internal classMyThread - { the Private intNumber =0; - Objectobj =New Object(); - - Public voidRun () + { - varTA =NewThread (printnumber); + varTB =NewThread (printnumber); A varTC =NewThread (printnumber); at -Ta. Start ("1"); -Tb. Start ("2"); -Tc. Start ("3"); - } - in Private voidPrintnumber (Objectnum) - { to for(inti =0; I <9; i++) + { - Lock(obj) the { * if(Convert.ToInt32 (num) = = number +1|| Convert.ToInt32 (num) = = number-2) $ {Panax Notoginseng Console.Write (num); -Number =Convert.ToInt32 (num); the + //notifies a waiting thread A Monitor.pulseall (obj); the } + Else - { $ //this round should not print the thread, let him wait for the notice outside the lock $ //because this time he also executed the judgment, so the cycle is one less -i--; - monitor.wait (obj); the } - }Wuyi } the } -}
Steal @ Song Xingju-sindrol Classmate's code: C # Add three threads to start executing a method at the same time, and then call the loop in a method in turn to print the output
C # 3 Threads a B C prints 123123123 sequentially.