Monday, 18 March 2013

Thread locking or Thread Synchronization

In the below Program all the three threads that are created in program are calling the same method for execution at the same time. So in this case if we execute the program and watch the output we will result that are unexpected.
The problem behind the execution is write now the method is a asynchronous method which can be called by multiple threads at a time.
To overcome the problem with asynchronous we need to first make the method as a synchronous method by adopting the process of thread locking or thread synchronous which can be done putting the methods under the special 'lock' block.
Uncomment the commented section and watch the output.

using System;
using System.Threading;


namespace CSharpConsole
{
    class ThreadDemo4
    {
        Thread t1, t2, t3;
        public ThreadDemo4()
        {
            t1 = new Thread(Display);
            t2 = new Thread(Display);
            t3 = new Thread(Display);
            t1.Start(); t2.Start(); t3.Start();

        }
        // Asynchronous Method
        public void Display()
        {
            Console.WriteLine("[CSharp is  ");
            Thread.Sleep(5000);
            Console.WriteLine("Object Oriented]");

        }
        /* Synchronous Method
        public void Display()
        {
            lock (this)
            {
                Console.Write("[ CSharp is ");
                Thread.Sleep(5000);
                Console.WriteLine("Object Oriented ]");
            }
        }*/
 
            static void Main()
        {
            ThreadDemo4 obj = new ThreadDemo4();
            obj.t1.Join(); obj.t2.Join(); obj.t3.Join();
            Console.ReadLine();
        }

    }
    
}

No comments:

Post a Comment