Extending by Thread class

Creating a thread by extending the Thread class in Java involves defining a subclass of Thread and overriding its run() method to specify the task the thread will perform. The thread is then instantiated and started using the start() method, which invokes run() in a separate thread.

Below is a detailed explanation followed by an example program demonstrating how to create and use a thread by extending the Thread class.

Steps to Create a Thread by Extending Thread

  1. Create a Subclass: Define a class that extends Thread.
  2. Override run(): Implement the run() method to define the task the thread will execute.
  3. Instantiate the Thread: Create an instance of the subclass.
  4. Start the Thread: Call the start() method to begin execution in a new thread.

Example Program

This program creates two threads by extending the Thread class. Each thread prints a message multiple times with a delay to simulate work.

public class ThreadByExtendingExample {
    // Custom thread class extending Thread
    static class MyThread extends Thread {
        // Constructor to set thread name
        public MyThread(String name) {
            super(name); // Set thread name
        }

        // Override run() to define thread's task
        @Override
        public void run() {
            for (int i = 1; i <= 3; i++) {
                System.out.println(getName() + " - Count: " + i);
                try {
                    Thread.sleep(1000); // Simulate work with 1-second delay
                } catch (InterruptedException e) {
                    System.out.println(getName() + " was interrupted");
                }
            }
            System.out.println(getName() + " has finished");
        }
    }

    public static void main(String[] args) {
        // Create two thread instances
        MyThread thread1 = new MyThread("Thread-One");
        MyThread thread2 = new MyThread("Thread-Two");

        // Set priorities (optional, for demonstration)
        thread1.setPriority(Thread.MAX_PRIORITY); // Priority 10
        thread2.setPriority(Thread.MIN_PRIORITY); // Priority 1

        // Start both threads
        System.out.println("Starting threads...");
        thread1.start();
        thread2.start();

        System.out.println("Main thread finished");
    }
}
/*
Starting threads...
Thread-One - Count: 1
Thread-Two - Count: 1
Thread-One - Count: 2
Thread-Two - Count: 2
Thread-One - Count: 3
Thread-Two - Count: 3
Thread-One has finished
Thread-Two has finished
Main thread finished
*/

When to Use

  • Use extending Thread when you need a simple thread with specific behavior and don’t need to inherit from another class.
  • For more flexibility (e.g., reusing tasks or using thread pools), prefer implementing Runnable or using ExecutorService.
Scroll to Top