【发布时间】:2017-05-03 12:08:40
【问题描述】:
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
【问题讨论】:
-
注意:
this是Runnable实例,而不是第 7 行的Thread。
标签: java multithreading synchronization java-threads synchronized-block