Multi Threaded Printing (Synchronizing Threads) : Lock : Thread C# Examples


C# Examples » Thread » Lock »

 

Multi Threaded Printing (Synchronizing Threads)









    
using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Threading;

public  class  Printer  {
        public  void  PrintNumbers()  {
                lock  (this)  {
                        Console.WriteLine("->  {0}  is  executing  PrintNumbers()",  Thread.CurrentThread.Name);
                        Console.Write("Your  numbers:  ");
                        for  (int  i  =  0;  i  <  10;  i++)  {
                                Random  r  =  new  Random();
                                Thread.Sleep(1000  *  r.Next(5));
                                Console.Write(i  +  ",  ");
                        }
                        Console.WriteLine();
                }
        }
}

class  Program  {
        static  void  Main(string[]  args)  {
                Printer  p  =  new  Printer();
                Thread[]  threads  =  new  Thread[10];
                for  (int  i  =  0;  i  <  10;  i++)  {
                        threads[i]  =  new  Thread(new  ThreadStart(p.PrintNumbers));
                        threads[i].Name  =  string.Format("Worker  thread  #{0}",  i);
                }
                foreach  (Thread  t  in  threads)
                        t.Start();
                Console.ReadLine();
        }
}
    
   
  
   




HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Thread
» Lock