Example 1: Two threads add and subtract the same variable without a thread lock
Static void Main (string[] args) { new Counter (); var New Thread (() = testcounter (counter)); var New Thread (() = testcounter (counter)); T1. Start (); T2. Start (); Thread.Sleep (Timespan.fromseconds (3)); // Sleep 3 seconds, ensure that T1, T2 two threads are complete Console.WriteLine (counter.count); Console.read ();}
The count variable is continuously added 1 minus 1, and the last count should be 0, but you can see that with two threads to do this, the result is not 0, an error occurs.
Example 2, using the thread lock, two threads to the same variable to add and subtract operations
Static void Main (string[] args) { new counterwithlock (); var New Thread (() = Testcounter (counterlock)); var New Thread (() = Testcounter (counterlock)); T1. Start (); T2. Start (); Thread.Sleep (Timespan.fromseconds (3)); // Sleep 3 seconds, ensure that T1, T2 two threads are complete Console.WriteLine (counterlock.count); Console.read ();}
With the thread lock, the result is normal, so adding the thread lock guarantees that there will be no error.
Class and method used in Example 1, example 2
/// <summary>///1000 Plus and minus operations on the same variable/// </summary>/// <param name= "C" ></param>Static voidTestcounter (Counterbase c) {Console.WriteLine ("Testcounter Start"); for(inti =0; I < +; i++) {c.increment (); C.decrement (); } Console.WriteLine ("Testcounter End");}
Abstract classcounterbase{ Public Abstract voidIncrement (); Public Abstract voiddecrement ();}/// <summary>///No Locks ./// </summary>classcounter:counterbase{ Public intCount {Get;Private Set; } Public Override voidIncrement () {count++; } Public Override voidDecrement () {count--; }}/// <summary>///Locking/// </summary>classCounterwithlock:counterbase {Private ReadOnly ObjectLocker =New Object(); Public intCount {Get;Private Set; } Public Override voidIncrement () {Lock(Locker) {count++; } } Public Override voidDecrement () {Lock(Locker) {count--; } }}
Why are objects that may be modified by multiple threads to be added to the lock