Java Program to create thread by extending Thread class

Program

class ExtendThread extends Thread
{
	public void run()
	{
		System.out.println("Printing from run():\t" + Thread.currentThread().getName());
	}
}
public class ThreadExtendsThreadClass
{
	public static void main(String[] args)
	{
		System.out.println("Threads: Extending Thread Class");
		System.out.println("Printing from main:\t" + Thread.currentThread().getName());
		ExtendThread extThread = new ExtendThread();
		extThread.start();
	}
}

This Java program demonstrates creating a thread by extending the Thread class.

  1. Thread Class Extension:

    • By extending the Thread class, the ExtendThread class inherits all its methods, including start() and run().
    • The start() method is used to begin the execution of the thread, which internally calls the run() method.
    • The ExtendThread class extends the Thread class, which allows it to represent a thread.
    • The run() method is overridden to define the task to be executed when the thread starts.
    • In the run() method, the program prints a message along with the name of the current thread using Thread.currentThread().getName().
  2. Main Class:

    • The main class, ThreadExtendsThreadClass, contains the main() method, which is the entry point of the program.
    • It first prints a message: "Threads: Extending Thread Class."
    • The main thread prints its name using Thread.currentThread().getName(), typically "main".
  3. Thread Creation and Execution:

    • An instance of ExtendThread is created, representing a new thread.
    • The start() method of the Thread class is called on the ExtendThread instance. This triggers the execution of the run() method in a separate thread.
    • Unlike implementing the Runnable interface, extending Thread ties the class to the threading behavior, limiting its ability to extend other classes (since Java does not support multiple inheritance).
  4. Output:

    • The main thread prints its name (main) as part of the main program execution.
    • The new thread prints its name when executing the run() method.

Output

Threads: Extending Thread Class
Printing from main:	main
Printing from run():	Thread-0