Code snip:
Code: Select all
public class TestClass
{
static StringBuffer sb1 = new StringBuffer();
static StringBuffer sb2 = new StringBuffer();
public static void main(String[] args)
{
new Thread
(
new Runnable()
{
public void run()
{
synchronized(sb1)
{
sb1.append("X");
synchronized(sb2)
{
sb2.append("Y");
}
}
System.out.println(sb1);
}
}
).start();
new Thread
(
new Runnable()
{
public void run()
{
synchronized(sb2)
{
sb1.append("Y"); //<- appends Y to sb1, not "appends Y to sb2"
synchronized(sb1)
{
sb2.append("X"); // <- appends X to sb2
}
}
System.out.println(sb2);
}
}
).start();
}
}
Explanation:
I think it must correct to:[...] Second thread acquires the lock of sb2 and appends Y to sb2.[...]