Java Program on Synchronization

Free Java courses with 37 real-time projects - Learn Java

Program 1

// Outer resource method
package dataflair;

public class MyTable 
{
    synchronized void showTable(int n)
    {
        try
       {    
         for (int i = 1; i <= 10; i++) 
         {
             System.out.println(n*i);
             Thread.sleep(1000);
         }
       }
       catch(InterruptedException e) 
       {
           System.out.println(e);
       }   
    }
}

Program 2

package dataflair;

public class MyThread extends Thread
{
       private MyTable M;
       private int n;
       MyThread(MyTable M,int n)
       {
           
           this.M=M;
           this.n=n;
           
       }
       public void run()
       {
           System.out.println("First Thread Starts: ");
           M.showTable(n);
           System.out.println("First Thread End: ");
       }
}

Program 3

package dataflair;

public class TestMain 
{
    public static void main(String[] args) throws InterruptedException
    {
           MyTable M=new MyTable();
           MyThread mt1=new MyThread(M, 5);
           MyThread1 mt2=new MyThread1(M, 7);
           mt1.start();
           mt2.start();
           mt1.join();
           mt2.join();
           //MyThread mt2=new MyThread(M, 7);
           
    }
    
}

Program 4

package dataflair;

public class MyThread1 extends Thread
{
    MyTable M;
    int n;
    MyThread1(MyTable M,int n)
    {
        this.M=M;
        this.n=n;
    }
    public void run()
    {
       System.out.println("Second Thread Starts: ");
       M.showTable(n);
       System.out.println("Second Thread End: ");
    }
    
}

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *