Advertisement
class B implements Runnable
{
public void run()
{
synchronized(this) //Synchronizing the object of B, this refers to ob
{
System.out.println("Thread2 running and printing table of 5");
for(int i=1; i<=10; i++)
{
System.out.println("5 x "+ i + " = " + (5*i));
}
} //synchronized block ends
}
}
class A
{
public static void main(String...ar)
{
B ob = new B();
Thread t= new Thread(ob , "newThread"); //Calling Thread's constructor & passing the object
//of B class that implemented Runnable interface
//& the name of new thread.
t.start();
synchronized(ob) //Synchronizing the object of B, ob
{
System.out.println("main thread running and printing table of 6");
for(int i=1; i<=10; i++)
{
System.out.println("6 x "+ i + " = " + (6*i));
}
} //synchronized block ends
}
}
main thread running and printing table of 6
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
newThread running and printing table of 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Advertisement
class B implements Runnable
{
public void run()
{
synchronized(this) //Synchronizing the object of B, this refers to ob
{
System.out.println("newThread running and printing table of 5");
for(int i=1; i<=10; i++)
{
System.out.println("5 x "+ i + " = " + (5*i));
}
notify(); //notifying the main thread to continue its work
} //synchronized block ends
}
}
class A
{
public static void main(String...ar)
{
B ob = new B();
Thread t= new Thread(ob , "newThread"); //Calling Thread's constructor & passing the object
//of B class that implemented Runnable interface
//& the name of new thread.
t.start();
synchronized(ob) //Synchronizing the object of B, ob
{
try
{
ob.wait(); //main thread stops its execution and waits until it is notify()
System.out.println("main thread running and printing table of 6");
for(int i=1; i<=10; i++)
{
System.out.println("6 x "+ i + " = " + (6*i));
}
}
catch(InterruptedException e)
{
System.out.println(e);
}
} //synchronized block ends
}
}
newThread running and printing table of 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
main thread running and printing table of 6
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement