Can anybody explain this code corresponding to deadlocks in Threads?
class syn1{
String msg;
syn1(String s){
msg = s;
}
synchronized void set(String t, syn1 a){
msg += "["+t;
a.get();//lock on other object.
try{
Thread.sleep(100);
}catch(Exception e){
System.out.println("Exception");
}
msg+="]";
}
synchronized String get(){
try{
Thread.sleep(100);
}catch(Exception e){
System.out.println("Exception");
}
return msg;
}
}
class Th1 implements Runnable{
syn1 s1;
syn1 s2;
Th1(syn1 s1, syn1 s2){
this.s1 = s1;
this.s2 = s2;
}
public void run(){
while(true){
s2.set((Thread.currentThread()).getName(), s1);
System.out.println(s2.get());
s1.set((Thread.currentThread()).getName(), s2);
System.out.println(s1.get());
}
}
}
class Dead{
public static void main(String args[]){
syn1 s1 = new syn1("s1 ");
syn1 s2 = new syn1("s2 ");
new Thread(new Th1(s1, s2), "T1").start();
new Thread(new Th1(s1, s2), "T2").start();//(1)
//comment the above line(1) and uncomment
//the Line(2) below to cause deadlock.
//new Thread(new Th1(s2, s1), "T2").start();//(2)
}
}