該示例說明了死鎖是如何發生的。有一件事我不明白,那就是當第一個調用實例alphone的方法bow的addad即將執行gaston.bowbBack(this)時,線程是否會釋放鎖並獲取實例gaston的鎖if ,假設它不屬於第二個線程?或者它會同時持有兩個鎖,直到方法的所有代碼完全執行?還有一個問題,有什麼辦法來檢查線程是否持有鎖?一個線程可以同時持有兩個鎖嗎?
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();
}
}
好隨時我看到這個例子出現我開始尋找關閉這個作爲重複,我們已經在這一個了很多。是的,沒有理由一次線程不能超過1個鎖。鏈接的帖子上的選定答案應該明確發生了什麼。 – 2014-12-04 14:47:06