Java Program on Synchronization
Get Job-ready: Java Course with 45+ 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: ");
}
}Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

