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);
}
}
}
如果我理解正确,那么在第 7 行同步块引用对象t1
,在第 15 行同步块也引用同一个对象,因此一次只有一个线程可以获取该对象的锁,其他线程必须等待。
那他们为什么要争执呢?输出混合像
thread B 62
thread B 63
thread B 64
thread A 0
thread A 1
thread A 2
thread B 65
thread A 3