Contents

Extending the Thread class in Java

Writen by: David Vlijmincx

Introduction

Using Java, there are two ways to implement a thread. You can implement the Runnable interface, or you can extend the Thread class. In this tutorial, we will delve into the latter approach of extending the Thread class to create threads.

Extending the thread class

Extending the Thread class is done by adding extends Thread after the class name. By extending the Thread class you can override the run method from this class. This is important because the Thread class has a start method that calls the run method you will override.

In the following example, you can see how extending the Thread class is done.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package org.example;

public class Main {
    public static void main(String[] args) {

        MyThreadClass threadClass = new MyThreadClass();
        threadClass.start();
    }
    
}

class MyThreadClass extends Thread{

    @Override
    public void run() {
        System.out.println("This runs in a child thread!");
    }
}

In the example, the MyThreadClass extends the Thread class and overrides the run method to print something to the console.

The run method only defines the action the thread is going to run, it is not running in a separate thread yet, only by calling the start method the actions defined in the overridden run method will run in a separate thread.

In the previous example, you will have two threads running at the same time: The parent thread and the child thread. The parent thread is running your application/ main method and the child thread will run what is inside the run method. The child thread is not a daemon thread. This means that the parent will wait for the child thread. In the case of the example code the parent thread will only exit if the main method and child thread are done.

Conclusion

This article showed you how to extend the thread class in Java. While implementing the Runnable interface gives you more options. It is important to know that it is also possible to extend the Thread class.

 




Questions, comments, concerns?

Have a question or comment about the content? Feel free to reach out!