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.