In my
previous post I have illustrated, how you can create a thread by implementing Runnable interface. In this post I will
detail on second approach of thread creation, by extending the Thread class itself.
Steps to create thread
by extending Thread class:
1. Create a new class that extends Thread class.
2. Override the run () method within the class that extends the Thread class.
3. Define the start () method within the class that extends the Thread class.
Consider the below example program where
the class MyThread extends the Thread class and creates a new thread
called Demo Child Thread.
package blog.exception.mainThread;
public class MyThread extends Thread
{
MyThread()
{
super("Demo Child Thread");// call to constructor of Thread class.
System.out.println("My Thread Name "+this);
start();
}
@Override
public void run()
{
try
{
for(int i=3; i>0 ;i--)
{
System.out.println("My Child Thread "+i);
Thread.sleep(500);
}
}
catch(InterruptedException ex)
{
System.out.println("error in child "+ex);
}
}
}
|
package blog.exception.mainThread;
public class DemoMyThread
{
public static void main(String[] args)
{
new MyThread(); // call to MyThread
constructor to create a new thread
try
{
for(int i=3;i>0;i--)
{
System.out.println("Main Thread "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ex)
{
System.out.println("error in main thread
"+ex);
}
System.out.println("Main Thread
Terminating");
}
}
|
Output:
My Thread Name Thread[Demo Child Thread,5,main]
Main Thread 3
My Child Thread 3
My Child Thread 2
Main Thread 2
My Child Thread 1
Main Thread 1
Main Thread Terminating
|