C # multi-thread Development 7: Use the Monitor class to synchronize multiple threads

Source: Internet
Author: User

C # multi-thread Development 7: Use the Monitor class to synchronize multiple threads

In the article "Synchronize multiple threads with the lock statement", use the lock statement to synchronize multiple threads to access critical resources.

The code for using the lock statement is as follows.

Private static object o = new object (); lock (o) {if (account> = 1000) {Thread. sleep (10); // a small ATM account-= 1000; pocket + = 1000 ;}}

Use the ILDASM tool to view the IL code corresponding to the above Code:


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + expires/expires + expires/fs8y1xMS/tcShozwvcD4KPHA + expires/expires + wP2zzNDyoaM8L3A + expires "brush: java; "> using System; using System. threading; namespace MonitorExample {class Program {static object o = new object (); static int account = 1000; // account static int pocket = 0; // pocket static void Main (string [] args) {int threadCount = 10; var threads = new Thread [threadCount]; for (int I = 0; I <threadCount; I ++) {threads [I] = new Thread (DoSafeWork); threads [I]. start () ;}for (int I = 0; I <threadCount; I ++) {threads [I]. join ();} Console. writeLine ("pocket =" + pocket);} public static void DoSafeWork () {Monitor. enter (o); try {if (account >= 1000) {Thread. sleep (10); // a small ATM account-= 1000; pocket + = 1000;} finally {Monitor. exit (o );}}}}Shows the program execution result.

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.