2015-04-12 42 views
1

這是我的示例線程代碼。什麼是正確的邏輯輸出,我得到的示例線程代碼

public class Deadlock { 
    static 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()); 
      synchronized(bower) { //this is the change 
       bower.bowBack(bower); 
      } 

     } 
     public 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) throws InterruptedException { 
     final Friend alphonse = 
      new Friend("Alphonse"); 
     final Friend gaston = 
      new Friend("Gaston"); 
     new Thread(new Runnable() { 
      public void run() { alphonse.bow(gaston); } 
     }).start(); 
//  Thread.sleep(20); 
     new Thread(new Runnable() { 
      public void run() { gaston.bow(alphonse); } 
     }).start(); 
    } 
} 

這會陷入僵局。 但是,如果我在它做一個小的改變。我不使用'bower'作爲同步塊的監視器,而是使用'this',它不會陷入死鎖。

public class Deadlock { 
    static 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()); 
      synchronized(this) { //This is the change. 
       bower.bowBack(bower); 
      } 

     } 
     public 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) throws InterruptedException { 
     final Friend alphonse = 
      new Friend("Alphonse"); 
     final Friend gaston = 
      new Friend("Gaston"); 
     new Thread(new Runnable() { 
      public void run() { alphonse.bow(gaston); } 
     }).start(); 
//  Thread.sleep(20); 
     new Thread(new Runnable() { 
      public void run() { gaston.bow(alphonse); } 
     }).start(); 
    } 
    } 

請幫我弄清楚上面這段代碼顯示的行爲背後的正確原因。

回答

1

所不同的是

synchronized(objectidentifier) { 
    // Access shared variables and other shared resources 
} 

在這裏,爲ObjectIdentifier是一個對象,其鎖與同步語句代表監視器相關聯的參考。

synchronized(bower)使用監視器從涼亭,它是一個不同的對象。 你爲涼亭製作了一個鎖。因爲兩個線程都將對象鎖定在另一個線程中,所以會發生死鎖。

並且synchronized(this)使用自己的監視器。你爲自己的物體鎖定。線程將對象鎖定在相同的線程中,並且沒有人在意。

如果我錯了,請糾正我!

+0

由於刪除synchronize(this)synchronize(bower)澄清我的困惑。 +1。 – Sadique

0

你想要達到的目標是,在向某人屈服時,你不能屈服。

我想補充​​到bowBack方法和bow...()

+0

你的方法會導致僵局。這與我的第一段代碼類似,我在bow()中使用了synchronized(bower)。 – Sadique

相關問題