Another Thread Synchronization in C#

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Threading;  
  7. namespace AnotherThreadSynchronization  
  8. {  
  9.     class Program  
  10.     {  
  11.         static object baton = new object();  
  12.         static Random rmd = new Random();  
  13.         static void Main(string[] args)  
  14.         {  
  15.             for (int i = 0; i < 6; i++)  
  16.             {  
  17.                 new Thread(AnotherThread)  
  18.                     .Start();  
  19.             }  
  20.         }  
  21.         static void AnotherThread()  
  22.         {  
  23.             Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "- First cell");  
  24.             lock(baton)  
  25.             {  
  26.                 Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "- Second cell");  
  27.                 Thread.Sleep(rmd.Next(2000));  
  28.                 Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "- Third cell");  
  29.             }  
  30.             Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "- Forth cell");  
  31.         }  
  32.     }  
  33. }  
Output:
-
3- First cell
5- First cell
7- First cell
8- First cell
6- First cell
4- First cell
3- Second cell
3- Third cell
3- Forth cell
5- Second cell
5- Third cell
5- Forth cell
7- Second cell
7- Third cell
7- Forth cell
8- Second cell
8- Third cell
8- Forth cell