什么被锁住?呵呵,当然是Singleton对象被锁住了。 不过在这样的情况下,不会产生竞争锁的问题。同一个线程中synchronized是可以重入的(reentry)。 为了明白这点,大家可以参见§JLS 14.18 The synchronized Statement有这样的解释: << A single thread may hold a lock more than once. >> << Acquiring the lock associated with an object does not of itself prevent other threads from accessing fields of the object or invoking unsynchronized methods on the object. >> 如果不允许单一线程sychronized重入的话,下面的例子就会造成死锁了。呵呵。 << class Test { public static void main(String[] args) { Test t = new Test(); synchronized(t) { synchronized(t) { System.out.println("made it!"); } } } } >>
TO foryouever(光速兔子) : 为什么不去争?因为A的所有调用者(包括递归调用)是同一个线程(Thread)。:)总之,大家可以记住这点: <<“同一个线程”中synchronized是可以重入的>>
你的解释不对。这个情况不会去竞争同一把锁。
while (size <= 0) {
synchronized(logs) {
size = logs.size();
} }
但想不通为什么不去争。请: xiaohaiz(老土进城,两眼通红) 解释一下。
不过在这样的情况下,不会产生竞争锁的问题。同一个线程中synchronized是可以重入的(reentry)。
为了明白这点,大家可以参见§JLS 14.18 The synchronized Statement有这样的解释:
<<
A single thread may hold a lock more than once.
>>
<<
Acquiring the lock associated with an object does not of itself prevent other threads from accessing fields of the object or invoking unsynchronized methods on the object.
>>
如果不允许单一线程sychronized重入的话,下面的例子就会造成死锁了。呵呵。
<<
class Test {
public static void main(String[] args) {
Test t = new Test();
synchronized(t) {
synchronized(t) {
System.out.println("made it!");
}
}
}
}
>>
为什么不去争?因为A的所有调用者(包括递归调用)是同一个线程(Thread)。:)总之,大家可以记住这点:
<<“同一个线程”中synchronized是可以重入的>>