The Java Thread class can be extended like all other classes in Java with the extends keyword. Extending the Thread class, overriding the run() method, and calling the start() method is another way to create a new Thread in Java.
Create a Java Thread by Extending the Thread Class?
Note: Implement the Runnable interface unless you want direct access (via inheritance) to the Thread class.
If you want direct access to the Thread class, you are welcome to use it. Fortunately, the basic implementation is nearly identical to the process of creating a Thread using the Runnable interface. When extending the Thread class, you must override the run() method in the Thread class and call the start() method in the parent Thread class.
class ExampleThread extends Thread {
// constructor
ExampleThread(String name) {
// call the constructor in the parent class
// and pass the name
super(name);
}
// override the run() method in
// the parent Thread class
@Override
public void run() {
// run whatever code you like
}
}
Here is another, more complete example that includes an ExampleController class that can be used to create the Thread. Notice when "** Main Thread End **" will print.
class ExampleController {
public static void main(String args\[\]) {
System.out.println("** Main Thread Start **");
MyFirstThread thread1
= new MyFirstThread("First Thread");
MyFirstThread thread2
= new MyFirstThread("Second Thread");
MyFirstThread thread3
= new MyFirstThread("Third Thread");
// notice when the next line prints
System.out.println("** Main Thread End **");
}
}
class MyFirstThread extends Thread {
// Constructor for MyFirstThread
MyFirstThread(String name) {
// pass the name of the thread
// to the super constructor
super(name);
// start the thread
start();
}
// run() is called automatically after start()
// this is overridden from the parent Thread class
// the code in the run() method is what will be
// run as an independent thread
@Override
public void run() {
System.out.println(getName() + " starting.");
try {
for(int count=0; count < 5; count++) {
Thread.sleep(400);
System.out.println("In " + getName()
+ ", count is " + count);
}
} catch(InterruptedException exc) {
System.out.println(getName() + " interrupted.");
}
System.out.println(getName() + " terminating.");
}
}
Similarly to implementing the Runnable class, the Thread class contains the abstract method run() that must be overridden when extending the class.
Summary: How to Extend the Java Thread Class?
- The Java Thread class is extended using the
extendskeyword - This is not the preferred method for creating threads in Java unless you need access to the Thread class
- The process of extending the
Threadclass is very similar to implementing theRunnableclass - The
run()method must be implemented when extending theThreadclass