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.
-
Thread Class Extension:
- By extending the
Thread
class, theExtendThread
class inherits all its methods, includingstart()
andrun()
. - The
start()
method is used to begin the execution of the thread, which internally calls therun()
method. - The
ExtendThread
class extends theThread
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 usingThread.currentThread().getName()
.
- By extending the
-
Main Class:
- The main class,
ThreadExtendsThreadClass
, contains themain()
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"
.
- The main class,
-
Thread Creation and Execution:
- An instance of
ExtendThread
is created, representing a new thread. - The
start()
method of theThread
class is called on theExtendThread
instance. This triggers the execution of therun()
method in a separate thread. - Unlike implementing the
Runnable
interface, extendingThread
ties the class to the threading behavior, limiting its ability to extend other classes (since Java does not support multiple inheritance).
- An instance of
-
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.
- The main thread prints its name (
Output
Threads: Extending Thread Class
Printing from main: main
Printing from run(): Thread-0