0

I was reading about Threads in java and creating a new thread by implementing the Runnable interface and using start() and run() functions.

My code is as followed:

class NewThread implements Runnable
{
    Thread t;

    NewThread()
    {
        t = new Thread(this,"Demo Thread");
        System.out.println("Child Thread: " + t);
        t.start();
    }
    public void run()
    {
        try
        {
        for(int i = 5; i > 0; i--)
        {   
            System.out.println("Child Thread: " + i);
            t.sleep(500);
        }
    }
    catch(InterruptedException e)
    {
        System.out.println("Exception Caught!");
    }
    System.out.println("Exiting child thread!");
    }
}

class Threads
{
public static void main(String args [])
{
    new NewThread();

    try
    {
        for(int i = 5; i > 0; i--)
        {
            System.out.println("Main thread: " + i);
            Thread.sleep(1000);
        }
    }
    catch(InterruptedException e)
    {
        System.out.println("Exception caught!");
    }
    System.out.println("Exiting main thread!");
    }
}

From the first line of the main function, the constructor of the NewThread class is called.

What I read is that

After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. In essence, start( ) executes a call to run( )

Then why does the main thread run just after the start() is called but not the child thread that is the run() function?

Following is the output:

C:\Users\Kaustubh Srivastava\Desktop\Java\Test>java Threads
Child Thread: Thread[Demo Thread,5,main]
Main thread: 5
Child Thread: 5
Child Thread: 4
Main thread: 4
Child Thread: 3
Child Thread: 2
Main thread: 3
Child Thread: 1
Exiting child thread!
Main thread: 2
Main thread: 1
Exiting main thread!
  • 1
    You call the Thread's `start` in it's constructor, so it's `run()` is executed immediately. – daniu Jan 10 '18 at 15:04
  • But it doesn't right according to the output? – Kaustubh Srivastava Jan 10 '18 at 15:09
  • Ok, "immediately" is the wrong word. The printing happens as soon as it's the newly started thread's turn to run, which may be before or after returning from the constructor. – daniu Jan 10 '18 at 15:12
  • Okay, got it. Thank you :) – Kaustubh Srivastava Jan 10 '18 at 15:18
  • It is a mistake to start a thread from within the constructor of an object that the thread can see. https://stackoverflow.com/a/5623327/801894 – Solomon Slow Jan 10 '18 at 15:30
  • Re, "What is the flow of control...?" The whole point of multi-threading is, each `thread.start()` call creates a _new_ flow of control. After your program starts the new thread, it has _two_ flows happening in parallel. – Solomon Slow Jan 10 '18 at 15:31
  • Okay. I understand that start() creates a separate call stack for the thread and then that runs in parallel. One for the main thread and one for the child. – Kaustubh Srivastava Jan 10 '18 at 15:54

1 Answers1

0

The core concept is that once you have called start on the child thread both threads are running in parallel.

What you see in your printout is that the main thread just happens to print it's first line first. It could just as easily be the child thread.

It's that in essence phrase that is difficult to grasp but once you understand that parallel threads run asynchronously so the order of thing they do becomes interleaved almost arbitrarily.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • So while running in parallel I have no control over which thread runs first? – Kaustubh Srivastava Jan 10 '18 at 15:10
  • @KaustubhSrivastava - Correct! Each thread will do its own thing in its own order as expected but they are both doing it at the same time. However, because they both share the same console their output comes through interleaved. – OldCurmudgeon Jan 10 '18 at 15:13