2080 5

BIT401 ยท 2080 ยท 5 marks

Write a Java program to create a multi-threaded programs by extending Thread class. Create at least three threads.

Write a Java program to create a multi-threaded programs by extending Thread class. Create at least three threads. [5]

Advanced Java ProgrammingChapter 8: Multithreading and ConcurrencyThread class and Runnable interface

Model Answer: Multi-threaded Program by Extending Thread Class

Program Code

// Define a custom thread class by extending Thread
class MyThread extends Thread {
    private String threadName;
    
    // Constructor
    public MyThread(String name) {
        this.threadName = name;
    }
    
    // Override run() method
    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(threadName + " is running - Count: " + i);
            try {
                // Sleep for 1 second
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
        System.out.println(threadName + " has finished execution");
    }
}

// Main class to create and start threads
public class MultiThreadedProgram {
    public static void main(String[] args) {
        // Create three thread objects
        MyThread thread1 = new MyThread("Thread-1");
        MyThread thread2 = new MyThread("Thread-2");
        MyThread thread3 = new MyThread("Thread-3");
        
        // Start all three threads
        thread1.start();
        thread2.start();
        thread3.start();
        
        System.out.println("Main thread continues...");
    }
}

Output (Sample)

Main thread continues...
Thread-1 is running - Count: 1
Thread-2 is running - Count: 1
Thread-3 is running - Count: 1
Thread-1 is running - Count: 2
Thread-2 is running - Count: 2
Thread-3 is running - Count: 2
...
Thread-1 has finished execution
Thread-2 has finished execution
Thread-3 has finished execution

Key Points Explained

  1. Extend Thread Class: MyThread extends the Thread class
  2. Override run() Method: Contains the code to be executed by the thread
  3. Create Thread Objects: Three separate instances (thread1, thread2, thread3) are created
  4. Call start() Method: Invokes the thread's execution; never call run() directly
  5. Concurrent Execution: All three threads run concurrently, producing interleaved output
  6. Thread.sleep(): Pauses thread execution for specified milliseconds

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.