2013-04-30 63 views
2
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()); 
      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) { 
     final Friend alphonse = 
      new Friend("Alphonse"); 
     final Friend gaston = 
      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(); 
    } 
} 

在線教程說此代碼中發生死鎖的位置? Java的

死鎖時運行,這是非常有可能的是,當他們嘗試調用bowBack兩個線程將被阻塞。這兩個塊都不會結束,因爲每個線程都在等待另一個線程退出低頭。

但我在這裏沒有看到任何相互依存關係。任何人都可以解釋死鎖的位置嗎?

+0

報價解釋它。 – 2013-04-30 02:59:05

+3

http://stackoverflow.com/questions/749641/trying-to-wrap-my-wee-brain-around-how-threads-deadlock?rq=1 – Thihara 2013-04-30 02:59:56

回答

1

這是一個典型的死鎖,2個線程+2個鎖。

1)線索1鎖阿方和移動到鎖定加斯

2)螺紋2鎖加斯並且移動到鎖定阿爾

3)線索1到達加斯但它是由線程2和線程1塊鎖定

4)螺紋2到達阿爾但它是由線程1鎖定,它阻止

在此處添加的延遲,以增加概率

public synchronized void bow(Friend bower) { 
    try { 
     Thread.sleep(100); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
...