Extending Thread Class to create threads in java.

To create Thread, we basically need to provide an implementation for run function.

We can do it in two ways. Either we can extend Thread class and override it’s run method or we can implement Runnable interface and provide an implementation for it’s abstract run method.

In this article, I am extending Thread class.

public class SimpleThread extends Thread {

}

We have extended Thread class. But, we have not overriden the run function. It is not an Error scenario, but it will not do anything. Because, default implementation of run in Thread class is empty.

To do anything useful, we have to provide an implementation for it.

public class SimpleThread extends Thread {
    @Override
    public void run() {
        System.out.println("Current Thread name :- " + Thread.currentThread().getName());
    }
}

Now, it’s time to test our Thread class.

public static void main(String ... args) {
    Thread t = new SimpleThread();
    
    //Set the name of this thread
    t.setName("SimpleThread Object" );

    //Start This Thread
    t.start();

    System.out.println("Current thread is - " + Thread.currentThread().getName());
}

This is a main function, which creates a thread instance and calls start() method on that object.

Remember, you need to call start() method to start a thread. Otherwise nothing will happen.

Complete Code

public class SimpleThread extends Thread {

    @Override
    public void run() {
    System.out.println("Current Thread name :- " + Thread.currentThread().getName());
    }

    public static void main(String ... args) {
    Thread t = new SimpleThread();
    t.setName("SimpleThread Object" );

    System.out.println("Current thread is - " + Thread.currentThread().getName());
    t.start();
    }
}

Output

Current Thread name :- SimpleThread Object
Current thread is - main