Basic 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 BasicThreadSynchronization  
  8. {  
  9.     class Program  
  10.     {  
  11.         static int count = 0;  
  12.         static object boton = new object();  
  13.         static void Main(string[] args)  
  14.         {  
  15.             Thread thread1 = new Thread(Increment);  
  16.             Thread thread2 = new Thread(Increment);  
  17.             thread1.Start();  
  18.             Thread.Sleep(500);  
  19.             thread2.Start();  
  20.         }  
  21.         static void Increment()  
  22.         {  
  23.             while (true)  
  24.             {  
  25.                 lock(boton)  
  26.                 {  
  27.                     int temp = count;  
  28.                     Thread.Sleep(1000);  
  29.                     count = temp + 1;  
  30.                     Console.WriteLine("theadID {1} - This is BasicThreadSynchronization: {0}", count, Thread.CurrentThread.ManagedThreadId);  
  31.                 }  
  32.                 Thread.Sleep(1000);  
  33.             }  
  34.         }  
  35.     }  
  36. }  
Output:
 
theadID 3 - This is BasicThreadSynchronization: 1
theadID 4 - This is BasicThreadSynchronization: 2
theadID 3 - This is BasicThreadSynchronization: 3
theadID 4 - This is BasicThreadSynchronization: 4
theadID 3 - This is BasicThreadSynchronization: 5
theadID 4 - This is BasicThreadSynchronization: 6
 ......