Check the foll code: it deadlocks because of sleep command in first
thread -
my question is
1. How can you have lock over sb2 and append sb1 and then have lock over sb1 and append sb2 ???
2. can you see the deadlock without the sleep command
3. with //1 - it deadlocks
4. with 2 and or 3 it prints only sb1 = X
pls explain - main question is part 1.
public class TestClassDeadlock
{
static StringBuffer sb1 = new StringBuffer();
static StringBuffer sb2 = new StringBuffer();
public static void main(
String[] args)
{
new Thread(new Runnable() {public void run()
{
synchronized(sb2) {sb1.append("X");
System.out.println("thread 1 appending X to sb1");
//try{Thread.sleep(5000);} catch(InterruptedException e){} //1
synchronized(sb1) {sb2.append("Y");
System.out.println("thread 1 appending Y to sb2");
}
}
//try{Thread.sleep(500);} catch(InterruptedException e){} // 2
System.out.println("This is sb1 :"+sb1);
}
}
).start();
new Thread(new Runnable(){public void run(){
synchronized(sb1){sb2.append("X");
System.out.println("thread 2 appending X to sb2");
synchronized(sb2){//try{Thread.sleep(500);} catch(InterruptedException e){}//3
sb1.append("Y");
System.out.println("thread 2 appending Y to sb1");
}
}
System.out.println("This is sb2 :"+sb2);
}
}
).start();
}
}