2016-06-11 113 views
0

以下是中的代碼片段實踐中的java併發性本書討論打開的調用。我沒有得到的一點是,setLocation方法被聲明,它已經同步,並再次調用同一個方法中的synchronized(this)塊,爲什麼這麼做?它是類型錯誤嗎?同步方法已經擁有這個方法的鎖定,那麼爲什麼同樣的對象呢?在同步方法內同步(this)塊

@ThreadSafe 
    class Taxi { 
     @GuardedBy("this") private Point location, destination; 
     private final Dispatcher dispatcher; 
     ... 
     public synchronized Point getLocation() { 
      return location; 
     } 
     public synchronized void setLocation(Point location) { 
      boolean reachedDestination; 
      synchronized (this) { 
       this.location = location; 
       reachedDestination = location.equals(destination); 
      } 
      if (reachedDestination) 
       dispatcher.notifyAvailable(this); 
     } 
    } 

回答

5

這是本書中的錯誤。見the errata

在代碼10.6中,Taxi.setLocation不應該是一個同步方法。 (然而,它的主體中的同步塊是正確的。)

+0

感謝Nizet打破了我的想法,認爲這樣的聲明有一些隱藏的含義,沒有考慮到勘誤。 – Curious