C # 3 Threads a B C prints 123123123 sequentially.

Source: Internet
Author: User

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.

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.