Thread Synchronization:
- Synchronization is the concept of allowing thread sequentially when multiple threads trying to access the resource.
- We implement synchronization using ‘synchronized’ keyword.
- We can synchronize either Block or Method.

using System; using System.Threading; public class LockDisplay { public void DisplayNum() { lock (this) { for (int i = 1; i <= 5; i++) { Thread.Sleep(100); Console.WriteLine(“i = {0}”, i); } } } } class Example { public static void Main(string[] args) { LockDisplay obj = new LockDisplay(); Thread t1 = new Thread(new ThreadStart(obj.DisplayNum)); Thread t2 = new Thread(new ThreadStart(obj.DisplayNum)); t1.Start(); t2.Start(); } } |