Sometimes we lock a piece of code may be based on the value of a variable, the same value does not allow two or more methods to run in parallel, I encountered in the work, there are 100 values, the same parameter values can not run in parallel.
There is a lock method recursive call will not deadlock, because it is necessary to lock the same variable. The answer, of course, is not deadlock.
Here is a test demo
classProgram {Private Static ObjectA =New Object(); Private Static Objectb =New Object(); Private Static Objectc =New Object(); Private StaticHashtable list = hashtable.synchronized (NewHashtable ()); Static voidMain (string[] args) { //All I unequal threads will execute synchronously and return the result NewThread (NewParameterizedthreadstart (Delegate(Objectobj) {Test (0, -); Console.WriteLine ("1"); })). Start (); NewThread (NewParameterizedthreadstart (Delegate(Objectobj) {Test (1, -); Console.WriteLine ("1+"); })). Start (); //all i==2 threads are executed sequentially NewThread (NewParameterizedthreadstart (Delegate(Objectobj) {Test (2, -); Console.WriteLine ("2"); })). Start (); NewThread (NewParameterizedthreadstart (Delegate(Objectobj) {Test (2, -); Console.WriteLine ("3"); })). Start (); NewThread (NewParameterizedthreadstart (Delegate(Objectobj) {Test (2, -); Console.WriteLine ("4"); })). Start (); NewThread (NewParameterizedthreadstart (Delegate(Objectobj) {Test (2, -); Console.WriteLine ("5"); })). Start (); NewThread (NewParameterizedthreadstart (Delegate(Objectobj) {Test (2, -); Console.WriteLine ("6"); })). Start (); //two times Lock the same variable does not deadlock NewThread (NewParameterizedthreadstart (Delegate(Objectobj) {Test2 (3, -); Console.WriteLine ("7"); })). Start (); Console.readkey (); } /// <summary> ///blocking for I same thread is guaranteed not to parallel multiple/// </summary> /// <param name= "i" ></param> /// <param name= "J" ></param> Public Static voidTest (intIintj) {if(!list. ContainsKey (i)) list. ADD (i, DateTime.Now); Lock(List[i]) {thread.sleep (j); } } //multiple Lock the same variable tests if deadlock Public Static voidTest2 (intIintJBOOLIsFirstRun =true) { if(!list. ContainsKey (i)) list. ADD (i, DateTime.Now); Lock(List[i]) {thread.sleep (j); if(IsFirstRun) Test2 (i, J,false); } } }
The program output is as follows:
1+2137456
Multithreaded linear lock