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!