HTML Java

Java Reentrance Synchronization


Reentrance synchronization vs Multiple Lock

In this a single thread can acquire more than 1 lock s first it acquire lock with s class and then string lock coder coder and then acquire class lock s for t1 and again get the same object lock at the same time not after realeasing the same object lock after completing 1 synchrnoize method I wiil give u example 2 for this you can see evening method is call inside the synchronized method so after complete this synchrnozed method it will acquire lock on same object its called Reinrance.

Example

package DemoThreads;
class Show{
public synchronized void goodMorning(String name) {
synchronized(name) {
synchronized(Show.class) {
for(int i = 0 ;i < 2 ;i++) {
System.out.println("Good Morning "+name);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
goodEvening();
}
}
}

public synchronized void goodEvening() {
System.out.println("Good Evening");
}
}

Example

class MyThread extends Thread{
Show s;
String name;
MyThread(Show s,String name){
this.s = s;
this.name = name;
}
public void run() {
s.goodMorning(name);
}
}
public class Threads{
public static void main(String args[]) throws InterruptedException {
Show s = new Show();
MyThread t1 = new MyThread(s,"ankit");
MyThread t2 = new MyThread(s,"agam");
t1.start();
t2.start();
}
}

Output

Good Morning ankit
Good Morning ankit
Good Evening ankit
Good Morning agam
Good Morning agam
Good Evening agam