Sunday, December 28, 2014

Program to lock a thread using C#

9:17 PM - By azeheruddin khan 1

Explanation: - In the Below given program, the keyword ‘this’ refers to the current thread object i.e. either ‘t1’ or ‘t2’. The statement: lock(this) means, the method: checkin( ) is locked for a particular thread, until that thread completes its execution, no other thread can access that method.  

Example:


using System.Threading;
using System;

namespace MultiThreadingWithLock
{
    class Program
    {
        static void Main(string[] args)
        {
            AirportCheck a=new AirportCheck();
            ThreadStart th=new ThreadStart(a.checkin);
            ThreadStart th1=new ThreadStart(a.checkin);
            Thread t1=new Thread(th);
            Thread t2=new Thread(th1);
            t1.Start();
            t2.Start();
            Console.ReadLine();

        }
    }

    class AirportCheck
    {
        static int i = 1;
        private Object thisLock = new Object();

        public void checkin()
        {
            lock (this)
                for (; i <= 5; i++)
                {
                    Console.WriteLine("passenger:" + i + " checks in");
                    Console.WriteLine("passenger:" + i + " gets into the plane");
                    Console.WriteLine();
                    Thread.Sleep(1000);
                }
            Console.WriteLine();
        }
    }

}


Outpu:






About the Author

I am Azeheruddin Khan having more than 6 year experience in c#, Asp.net and ms sql.My work comprise of medium and enterprise level projects using asp.net and other Microsoft .net technologies. Please feel free to contact me for any queries via posting comments on my blog,i will try to reply as early as possible. Follow me @fresher2programmer
View all posts by admin →

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

1 comments:

adsense

© 2014 Fresher2Programmer. WP Theme-junkie converted by Bloggertheme9
Powered by Blogger.
back to top