Java program to create a thread by extending the Thread class

Java example to create a thread by extending the Thread class.
Submitted by Nidhi, on April 06, 2022

Problem Solution:

In this program, we will extend the Thread class and override the run() method. Here, we used the start() method to execute the thread. (Learn: Java Thread run() vs start() Methods)

Program/Source Code:

The source code to create a thread by extending the Thread class is given below. The given program is compiled and executed successfully.

// Java program to create a thread by extending 
// the Thread class

public class Main extends Thread {
  public static void main(String[] args) {
    Main thrd = new Main();

    thrd.start();

    System.out.println("Outside the thread");
  }

  public void run() {
    System.out.println("Thread Executed");
  }
}

Output:

Outside the thread
Thread Executed

Explanation:

In the above program, we created a class Main by extending the Thread class and overriding the run() method. The Main class also contains a method main(). The main() method is an entry point for the program. Here, we created the object of the Main class and used the start() method to execute the thread.

Java Threading Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.