Creating Multiple Threads

Creating multiple threads by extending the Thread class in Java involves defining a subclass of Thread, overriding its run() method, and creating multiple instances of that subclass to run concurrently. Each thread executes its own task independently, allowing parallel execution of tasks.

Below is an explanation followed by an example program that demonstrates creating and running multiple threads by extending the Thread class.

Steps to Create Multiple Threads

  1. Define a Thread Subclass: Create a class that extends Thread and overrides the run() method to specify the task.
  2. Create Multiple Instances: Instantiate multiple objects of the subclass, each representing a separate thread.
  3. Start the Threads: Call start() on each thread to begin concurrent execution.
  4. (Optional) Synchronize or Coordinate: Use methods like join() to wait for threads to complete or synchronization mechanisms for shared resources.

Example Program

This program creates three threads by extending the Thread class. Each thread performs a task (printing a message with a counter) with a delay to simulate work. The main thread waits for all threads to finish using join().

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

        // Override run() to define the thread's task
        @Override
        public void run() {
            for (int i = 1; i <= 4; i++) {
                System.out.println(getName() + " - Task count: " + i);
                try {
                    Thread.sleep(800); // Simulate work with 0.8-second delay
                } catch (InterruptedException e) {
                    System.out.println(getName() + " was interrupted");
                    return; // Exit if interrupted
                }
            }
            System.out.println(getName() + " has completed its task");
        }
    }

    public static void main(String[] args) {
        // Array of names including requested names
        String[] threadNames = {"Mahesh", "Paani", "Datta", "LotusPrince", "Sita"};

        // Create an array to store threads
        IndianThread[] threads = new IndianThread[threadNames.length];

        // Create and initialize threads
        for (int i = 0; i < threadNames.length; i++) {
            threads[i] = new IndianThread(threadNames[i]);
            // Set varying priorities for demonstration
            threads[i].setPriority(Thread.MIN_PRIORITY + (i % 10));
        }

        // Start all threads
        System.out.println("Starting all threads...");
        for (IndianThread thread : threads) {
            thread.start();
        }

        // Main thread waits for all threads to complete
        try {
            for (IndianThread thread : threads) {
                thread.join();
            }
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted");
        }

        System.out.println("All threads have finished. Main thread exiting.");
    }
}
/*
Starting all threads...
Mahesh - Task count: 1
Paani - Task count: 1
Datta - Task count: 1
LotusPrince - Task count: 1
Sita - Task count: 1
Mahesh - Task count: 2
Paani - Task count: 2
Datta - Task count: 2
LotusPrince - Task count: 2
Sita - Task count: 2
Mahesh - Task count: 3
Paani - Task count: 3
Datta - Task count: 3
LotusPrince - Task count: 3
Sita - Task count: 3
Mahesh - Task count: 4
Paani - Task count: 4
Datta - Task count: 4
LotusPrince - Task count: 4
Sita - Task count: 4
Mahesh has completed its task
Paani has completed its task
Datta has completed its task
LotusPrince has completed its task
Sita has completed its task
All threads have finished. Main thread exiting.
*/
Scroll to Top