Wednesday, 5 March 2025

Write a java program using multithreading to execute the threads sequentially using synchronized method



// Class that extends Thread and defines the run method

class MyThread extends Thread {

    private String name;


    public MyThread(String name) {

        this.name = name;

    }


    // Synchronized method to ensure sequential execution

    private static synchronized void printMessage(String msg) {

        System.out.println(msg);

        try {

            Thread.sleep(500); 

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }


    public void run() {

        printMessage("Thread " + name + " is running");

    }

}


// Class containing the main method

public class MainThread {

    public static void main(String[] args) {

        MyThread t1 = new MyThread("A");

        MyThread t2 = new MyThread("B");

        MyThread t3 = new MyThread("C");


        t1.start();

        t2.start();

        t3.start();

    }

}