2

Code :

public class ThreadNaming extends Thread{
public void run()
{
    System.out.println("running");
}

public static void main(String[] args)
{
    ThreadNaming t1 = new ThreadNaming();

    t1.start();

    System.out.println(t1.getName());   
}   
}

Doubt : According to my understanding a thread starts executing the main function , once t1.start() is encountered a new call stack and a new thread is created . This newly created thread executes the run method , then control returns to original thread executing the main() function and next System.out.println(t1.getName()) is executed so according to this flow output should be :

running Thread-0

but eclipse is showing the following output

Thread-0 running

I have googled flow control of thread but didnt get anything and i am unable to understand why this is happening ? can anyone explain the reason for it with proper flow of control ?

Note : Thread-0 is name of thread

Unique Part : i don't want to implement the behaviour described in the other question , i want to know the reason how main thread and new thread are executing simultaneously because i read in a tutorial that a scheduler can only execute a single thread at a time .

1 Answers1

0

From what I gather it is entirely plausible that this happens.
At the beginning of main, the main thread is running. Then you create an instance of your ThreadNaming class. On the next line you call t1.start(); which starts a new thread.

While this is called though, your main Thread can/will still run, calling System.out.println(t1.getName()); before it gets to System.out.println("running"); inside the ThreadNaming class. There is absolutely no guarantee that run() will be performed before the getName() call.

In order to force synchronization between your threads you will have to use some other methods such as wait (with notify) and join.

Note: you are usually better off implementing Runnable than extending Thread.

Community
  • 1
  • 1
Idos
  • 15,053
  • 14
  • 60
  • 75
  • but in a tutorial i studied that a scheduler can execute only a single thread at a time . now if this is correct then how main thread is executing while new thread is being created ? – user3442701 Feb 17 '16 at 10:41
  • They can run simultaneously if you have a multiprocessor computer (but even if you don't, Java can still choose whichever Thread to run at a given time, meaning your output is still ok) – Idos Feb 17 '16 at 10:42