Wednesday, 5 March 2025

Write a java program for the implementation of synchronization


class PrintTable {    

    // Synchronized method to print multiplication table

    public synchronized void printTable(int n) {  

        System.out.println("Table of " + n);

        for (int i = 1; i <= 10; i++) {

            System.out.println(n * i);

            try {  

                Thread.sleep(500);  // Pause for 500 milliseconds

            } catch (InterruptedException e) {

                System.out.println(e);

            }          }           }  }  



class TableThread extends Thread {  

    PrintTable pt;  

    int number;

    TableThread(PrintTable pt, int number) 

        {  

        this.pt = pt;  

        this.number = number;

    }  

    public void run() {  

        pt.printTable(number);  

    }        

}  

public class MultiThreadExample1 {  

    public static void main(String args[]) {

        PrintTable obj = new PrintTable();  

        // Creating and starting threads

        TableThread t1 = new TableThread(obj, 2);  

        TableThread t2 = new TableThread(obj, 5);  

    t1.start();  

        t2.start();  

    }  

}