Class Level Synchronization

ClassLevelSyncpackage classlevelsync;

public class ClassLevelSync {

public static void main(String[] args) {
weddingWish ww = new weddingWish();
person p1 = new person(ww,”Sam”);
person p2 = new person(ww,”Amit”);
p1.start();
p2.start();
}

}

class weddingWish{
private String name;
public void wish(String name){
synchronized(weddingWish.class){//class level lock is used.
this.name = name;
System.out.println(“Friends Congratulating : “+name);
for(int i=0; i<5; i++){
System.out.print("Happy marriage Day :");
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(name);
}
}
}
}

class person extends Thread{
private weddingWish ww;
private String name;
person(weddingWish ww, String name){
this.ww = ww;
this.name = name;
}
public void run(){
ww.wish(name);
}
}

Leave a Reply