Sunday, December 7, 2014

Execution of multiple threads using C#

12:22 AM - By azeheruddin khan 0

Explanation: - When two or more threads are executing simultaneously, then equal priority is given to both threads. Sleep( ) method is a static method of Thread class used for deactivating a thread for a certain period of time. As equal priority is given to both the threads: ‘t1’ and ‘t2’, we get wrong output as shown below, as there is no Synchronization between the two threads. Both the threads ‘t1’ and ‘t2’are executing checkin( ) method simultaneously.  So in order to achieve synchronization, we need to lock this method for a thread at a particular instance of time, which is possible by using lock keyword.

Example:

using System;
using System.Threading;

namespace MultipleThreadsExample
{
    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;

        public void checkin()
        {
            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();
        }
    }
}


Output:











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

0 comments:

adsense

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