Use lock to synchronize access to an object : Lock : Thread C# Examples


C# Examples » Thread » Lock »

 

Use lock to synchronize access to an object









    
using  System;  
using  System.Threading;  
  
class  MyThread  {    
    public  Thread  thrd;    
  
    public  MyThread(string  name,  int[]  nums)  {    
        thrd  =  new  Thread(this.run);  
        thrd.Name  =  name;  
        thrd.Start();
    }    
    
    void  run()  {    
        int  answer  =  sumIt(10);                      
    }    
    public  int  sumIt(int  nums)  {    
        lock(this)  {  
              Console.WriteLine(Thread.CurrentThread.Name);    
              Thread.Sleep(100);
            }    
            return  0;  
    }  
}    

    
    
class  MainClass  {    
    public  static  void  Main()  {    
        int[]  a  =  {1,  2,  3,  4,  5};    
    
        MyThread  mt1  =  new  MyThread("Child  #1",  a);    
        MyThread  mt2  =  new  MyThread("Child  #2",  a);    
    
        mt1.thrd.Join();    
        mt2.thrd.Join();    
    }    
}
    
   
  
   



Output

Child #1
Child #2


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Thread
» Lock