C # demonstration of multi-thread Competition

Source: Internet
Author: User

Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. text; <br/> using system. diagnostics; <br/> using system. threading; </P> <p> namespace multithreading <br/> {<br/> demonstration of class competing states <br/>{< br/> Public static void main () <br/>{< br/> stateobject state = new stateobject (); </P> <p> // start 20 threads, shared operation state object <br/> for (INT I = 0; I <20; I ++) <br/> {<br/> thread t = new t Hread (New samplethread (). racecondition); <br/> T. name = I. tostring (); <br/> T. start (State); <br/>}</P> <p> // The result shows that the frequency is not equal to 6. <Br/> // The reason is that after a thread executes if (State = 5), the thread does not have time to execute the command downward and is under control by other threads. <Br/> // when it is the second turn of this thread, the state has changed to 7, so there is a race state problem .. Use assertions to display <br/>}</P> <p> class stateobject <br/>{< br/> private int state = 5; </P> <p> Public void changestate (INT loop) <br/> {<br/> If (State = 5) <br/> {<br/> state ++; <br/> // if the value is not 6, execute the asserted display. <br/> trace. assert (State = 6, "the result is not 6 and appears in" + loop + "thread name:" + thread. currentthread. name); <br/>}</P> <p> state = 5; <br/>}</P> <p> class samplethread <br/>{< br/> Public void racecondition (Object O) <br/>{< br/> trace. assert (O is stateobject, "the input parameter must be of the stateobject type"); <br/> stateobject state = O as stateobject; </P> <p> int I = 0; <br/> while (true) <br/>{< br/> state. changestate (I ++); <br/>}</P> <p >}< br/>

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.