Sun爲什麼不使用synchronized(this)而不是mutex = this
,然後使用synchronized(mutex)?
我看不出他們做了什麼好處嗎?我錯過了什麼嗎?爲什麼SynchronizedCollection會將它分配給互斥量?
static class SynchronizedCollection<E> implements Collection<E>, Serializable {
private static final long serialVersionUID = 3053995032091335093L;
final Collection<E> c; // Backing Collection
final Object mutex; // Object on which to synchronize
SynchronizedCollection(Collection<E> c) {
if (c==null)
throw new NullPointerException();
this.c = c;
mutex = this;
}
SynchronizedCollection(Collection<E> c, Object mutex) {
this.c = c;
this.mutex = mutex;
}
public int size() {
synchronized (mutex) {return c.size();}
}
public boolean isEmpty() {
synchronized (mutex) {return c.isEmpty();}
}
儘量不要問問「Sun爲什麼要這樣做」,因爲只有Sun的開發人員才能回答這個問題。另外,你如何驗證你得到的答案是正確的?因此,這個問題可能沒有任何「正確的」答案。 – Patrick