Click here to Skip to main content
15,917,062 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Can Anyone explain how does work following code:



class Threading1
    {
        static void Main()
        {
            ThreadStart job = new ThreadStart(ThreadJob);
            Thread thread = new Thread(job);
            thread.Start();

            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine("First Thread: {0}", i);
                Thread.Sleep(1000);
            }
        }

        static void ThreadJob()
        {
            for (int i = 0; i < 8; i++)
            {
                Console.WriteLine("Remaining Threads: {0}", i);
                Thread.Sleep(500);
            }
        }
    }
Posted

1 solution

This code simply starts ONE thread which logs the line "Remaining Threads: {x}" 8 times with a 500ms pause between, while the line "First Thread:{x}" is logged several times with a 1000ms pause in between. The log strings are actually leading to the wrong assumption that you are starting several threads, which is clearly not the case.
The main function also does not wait for the actual ONE thread to be finished, so it is not sure that the thread is done at the end of Main().
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900