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