public class SynchronizedTest
{
public static void main(String argv[])
{
Thread t1 = new Thread(new Runnable(){public void run()
{
synchronized (this) //line 7
{
for(int i=0; i<100; i++)
System.out.println("thread A "+i);
}
}});
t1.start();
synchronized(t1) // line 15
{
for(int i=0; i<100; i++)
System.out.println("thread B "+i);
}
}
}
If I understand it correctly, then at line 7 synchronised block references object t1
and at line 15 synchronised block also references the same object so that only one of the threads at a time can acquire a lock on this object and other has to wait.
Then why their contend with each other? Output is mixed like
thread B 62
thread B 63
thread B 64
thread A 0
thread A 1
thread A 2
thread B 65
thread A 3