C # multi-thread synchronization attribute operations

Source: Internet
Author: User

Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. text; <br/> using system. threading; </P> <p> namespace multithreading <br/> {<br/> class thread sub-attributes <br/> {<br/> Private Static person per = new person (); </P> <p> Public static void main () <br/> {</P> <p> for (INT I = 0; I <10; I ++) <br/>{< br/> New thread (personthread ). start (); <br/>}</P> <p> thread. sleep (1000); </P> <p> console. writeline (Per. age); </P> <p> console. readline (); <br/>}</P> <p> Public static void personthread () <br/>{< br/> for (INT I = 0; I <5000; I ++) <br/>{< br/> // we have used lock in the age attribute, but even so, also, a race status problem may occur. <br/> // The reason is that in + =, get first and then set. The thread may still get the temporary value. <br/> // Therefore, add lock to the call, and then remove <br/> // lock (PER) <br/> // {<br/> // per. age + = 1; <br/>//} <br/> // Of course, we can also provide a secure thread increment method for person <br/> Per. incrementage (); <br/>}</P> <p> class person <br/>{< br/> private int _ age; <br/> private object sync = new object (); </P> <p> Public int age <br/> {<br/> Get <br/> {<br/> // lock (Sync) <br/> // {<br/> return this. _ age; <br/> //} <br/>}</P> <p> // set <br/> // {<br/> /// lock (sync) <br/> /// {<br/> // This. _ age = value; <br/>////} <br/>/}< br/>}</P> <p> Public int incrementage () <br/>{< br/> lock (Sync) <br/>{< br/> return ++ this. _ age; <br/>}< 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.