Creating a thread by extending Thread class

Extending the Thread is also one of the way of creating a thread.

class NewThread extends Thread
{
public NewThread()
{
// Set a name to child thread
setName("Child Thread");
}
public void run()
{
try
{
for(int i=5;i>=1;i--)
{
System.out.println(getName()+": "+i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println("Child thread interrupted.");
}
}
}
class ExtendThreadDemo
{
public static void main(String args[])
{
// Get current thread's object
Thread mainThread=Thread.currentThread();
// Set a name to main thread
mainThread.setName("Main Thread");
// Create child thread object and start
new NewThread().start();
// Start the loop
try
{
for(int i=5;i>=1;i--)
{
System.out.println(mainThread.getName()+": "+i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println("Main thread interrupted.");
}
}
}
-----------------------------------------
Output :
-----------------------------------------

Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Main Thread: 3
Child Thread: 3
Main Thread: 2
Child Thread: 2
Child Thread: 1
Main Thread: 1