C #3 threads a B C print 123123123 in sequence ..,

Source: Internet
Author: User

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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.