The lock keyword marks a statement block as a critical section by obtaining a mutex for a given object, executing the statement, and then releasing the lock.
classProgram {Static voidMain (string[] args) {Thread T=NewThread (lockobject.monitorincrement); Thread T1=NewThread (NewThreadStart (lockobject.lockincrement)); T.start (); T1. Start (); } } Public classLockObject {/// <summary> ///multi-threaded shared data/// </summary> Private Static intCounter =0; /// <summary> ///synchronizing objects, recommending this notation///you should avoid locking the public type, or the instance will go beyond the control of your code///details such as: Lock (This), Lock (typeof (MyType)) and lock ("MyLock")/// </summary> Private ReadOnly Static ObjectSynisynchronize =New Object(); Public Static voidmonitorincrement () {///Monitor.Enter and Monitor.Exit are equivalent to lockMonitor.Enter (synisynchronize); Thread.Sleep ( +); Counter++; Console.WriteLine ("monitorincrement counter={0}", counter); Monitor.Exit (synisynchronize); } Public Static voidlockincrement () {///Lock calls Monitor.Enter at the beginning///call Monitor.Exit at the end. Lock(synisynchronize) {counter++; Console.WriteLine ("lockincrement counter={0}", counter); } } }
The results of the operation are as follows:
C # 's Lock