Wednesday, 5 March 2025

Write a java program for the implementation of synchronization


Synchronization means only one thread can use the method at a time.

synchronized keyword is used to avoid data conflict.



import java.lang.*;


class Table

{

    // synchronized method

    synchronized void printTable(int n)

    {

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

        {

            System.out.println(n + " x " + i + " = " + (n*i));

        }

    }

}


// Thread 1

class MyThread1 extends Thread

{

    Table t;


    MyThread1(Table t)

    {

        this.t = t;

    }


    public void run()

    {

        t.printTable(5);

    }

}


// Thread 2

class MyThread2 extends Thread

{

    Table t;


    MyThread2(Table t)

    {

        this.t = t;

    }


    public void run()

    {

        t.printTable(10);

    }

}

class SyncDemo

{

    public static void main(String args[])

    {

        Table obj = new Table();


        MyThread1 t1 = new MyThread1(obj);

        MyThread2 t2 = new MyThread2(obj);


        t1.start();

        t2.start();

    }

}