2016-03-31 80 views
0

最近,我有機會從Java文檔here中查看材料。它包含以下代碼;嵌套類同步

public class AnotherDeadlockCreator { 

class Friend { 

    private final String name; 

    public Friend(String name) { 
     this.name = name; 
    } 

    public String getName() { 
     return this.name; 
    } 

    public synchronized void bow(Friend bower) { 
     System.out.format("%s: %s" 
      + " has bowed to me!%n", 
      this.name, bower.getName()); 
     bower.bowBack(this); 
    } 

    public synchronized void bowBack(Friend bower) { 
     System.out.format("%s: %s" 
      + " has bowed back to me!%n", 
      this.name, bower.getName()); 
    } 
} 

public static void main(String[] args) { 

    AnotherDeadlockCreator obj = new AnotherDeadlockCreator(); 

    final AnotherDeadlockCreator.Friend alphonse = 
     obj.new Friend("Alphonse"); 

    final AnotherDeadlockCreator.Friend gaston = 
      obj.new Friend("Gaston"); 

    new Thread(new Runnable() { 
     public void run() { alphonse.bow(gaston); } 
    }).start(); 


    new Thread(new Runnable() { 
     public void run() { gaston.bow(alphonse); } 
    }).start(); 
} 

}

除此之外,我讀過鎖定在「此」嵌套類的嵌套類同步鎖。請參閱以下內容;

Locking and synchronization between outer and inner class methods?

現在我不明白的是 - 當我們運用上述要求(關於嵌套類鎖)死鎖代碼,如何這會最有可能導致死鎖?我的意思是,如果線程訪問不同對象上的嵌套類的同步方法,死鎖將如何發生?我錯過了一些重要的東西嗎?

謝謝。

回答

0

bow()和bowBack()在Friend實例的同一個對象上同步:alphonse和gaston。

這裏是僵局的一個例子:

alphonse.bow(gaston) is invoked at time T. (alphonse synch started) 
gaston.bow(alphonse) is invoked at time T + 1. (gaston synch started) 
gaston.bowBack(alphonse) is invoked at time T + 2. (gaston synch already taken...waiting) 
alphonse.bowBack(gaston) is invoked at time T + 3. (alphonse synch already taken...waiting) 

--DeadLock。

+0

是的,絕對。但這不應該導致這裏的僵局。看,通過兩個線程調用的對象是不同的,所以它們有不同的作用域 - 不共享。因此,除非方法不是靜態的,否則鎖不應該停下來等待其他人完成。 – zgulser