Thread Synchronization
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
/*When we have multiple threads that share data, we need to provide synchronized access to the data.
* We have to deal with synchronization issues related to concurrent access to variables and objects accessible
* by multiple threads at the same time. This is controlled by giving one thread a chance to acquire a lock on the shared resource at a time*/
class SyncThread
{
static void Main(string[] args)
{
Launcher la = new Launcher();
Thread firstThread = new Thread(new ThreadStart(la.Coundown));
Thread secondThread = new Thread(new ThreadStart(la.Coundown));
Thread thirdThread = new Thread(new ThreadStart(la.Coundown));
firstThread.Start();
secondThread.Start();
thirdThread.Start();
Console.ReadLine();
}
}
class Launcher
{
public void Coundown()
{
lock (this)
{
Console.WriteLine("Thread has started");
for (int i = 2; i >= 0; i--)
{
Console.WriteLine("{0} Seconds to Finish", i);
Thread.Sleep(1000);
}
Console.WriteLine("Finished !!!");
}
}
}
Output:
Thread has started
2 Seconds to Finish
1 Seconds to Finish
0 Seconds to Finish
Finished !!!
Thread has started
2 Seconds to Finish
1 Seconds to Finish
0 Seconds to Finish
Finished !!!
Thread has started
2 Seconds to Finish
1 Seconds to Finish
0 Seconds to Finish
Finished !!!