Reputation: 1970
I was reading Multithreading from The Complete Reference and then I was struck at this code,I am unable to understand the output of this code.Can somebody help me with this?
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);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class First
{
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("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
It produces the output:
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
Main thread exiting
From the main() method,the NewThread() constructor is called and then an instance of Thread class is created named "demo thread" and the first print() statement gets executed.After that the start() method is called.Is this start method not supposed to call run() method implicitly and so the child loop should be executed,but according to the output the control goes in the main loop.How can the control go to the main() loop,even if we are calling t.start()?Can somebody please clarify the code output to me please?
Upvotes: 0
Views: 62
Reputation: 101820
Once start()
is called, there are now two threads running simultaneously. start()
returns immediately and the main loop continues (one loop very 1000mS). But the child loop is now running at the same time also - one loop every 500mS. So, until each loop finishes, there will be two child lines printed for every main line.
Upvotes: 3
Reputation: 77177
Unless there's a happens-before relationship, the order of execution of independent threads is nondeterministic; this is what makes concurrency challenging. After t.start()
is called, there's no relationship at all between the main thread and the thread in t
, and in the unlikely case where the system is heavily loaded, one thread or the other could theoretically complete all in sequence before control returns to the other thread at all.
Upvotes: 1