Sunday, December 19, 2010

Creating multiple threads in console Application.

You can create multiple threads in a program by extending the Thread class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

    class ThreadSchedule
    {
        public static void ChildThread1()
        {
            Console.WriteLine("child thread 1 started");
            Console.WriteLine("Child thread - counting from 1 to10");
            for(int T=1; T<11;T++)
            {
                for (int Cnt = 0; Cnt < 100; Cnt++)
                {
                    Console.Write(".");
                    //code to imitate work being done.
                }
                Console.Write("{0}",T);
            }
            Console.WriteLine("Child thread 1 finished");
        }
        public static void childThread2()
        {
            Console.WriteLine("Child thread 2 started");
            Console.WriteLine("Child thread - counting slowly from 11 to 20");
            for (int T = 11; T < 20; T++)
            {
                for (int Cnt = 0; Cnt < 100; Cnt++)
                {
                    Console.WriteLine(".");
                    //Code to imitate work being done.
                }
                Console.Write("{0}", T);
            }
            Console.WriteLine("Child thread 2 finished");
        }

       public static void Main()
        {
            ThreadStart Child1 = new ThreadStart(ChildThread1);
            ThreadStart Child2 = new ThreadStart(childThread2);

            Console.WriteLine("Main  - Creating child threads");

            Thread Thread1 = new Thread(Child1);
            Thread Thread2 = new Thread(Child2);

            Thread1.Start();
            Thread2.Start();
            Console.ReadLine();

        }
    }

 Output is display below:

No comments:

Recent Posts