Wednesday, 5 March 2025

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



/

import java.lang.*;


class Display

{

    // synchronized method

    synchronized void printMessage(String msg)

    {

        for(int i = 1; i <= 5; i++)

        {

            System.out.println(msg + " : " + i);

        }

    }

}

class MyThread extends Thread

{

    Display d;

    String message;


    MyThread(Display d, String message)

    {

        this.d = d;

        this.message = message;

    }


    public void run()

    {

        d.printMessage(message);

    }

}

class SyncExample

{

    public static void main(String args[])

    {

        Display obj = new Display();


        MyThread t1 = new MyThread(obj, "First Thread");

        MyThread t2 = new MyThread(obj, "Second Thread");


        t1.start();

        t2.start();

    }

}