我要去通過Oracle文檔的僵局.. 我發現這個代碼這個java代碼如何產生死鎖?
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();
}
}
我不理解,會發生什麼情況僵局?
我運行此代碼,它工作正常。所以當發生僵局時,肯定會有一些特別的事件呢?
假設首先在alphonse
對象上調用弓,當在對象對象上調用bower.bowBack(this)
時,它會將其鎖定在alphonse
對象上嗎? 因爲如果保留其鎖定,另一個對象bow
功能不會得到鎖直到alphonse
離開其鎖定,這將永遠是一個死鎖情況..
你是什麼意思,它運行良好,請發佈輸出,也許你只會認爲它運行良好 – AlexWien
而這就是僵局! 「向我鞠躬」的信息在哪裏? – AlexWien
對不起,有時它給了阿爾方斯:加斯東向我鞠躬!加斯東:阿爾方斯向我鞠躬!加斯東:阿爾方斯向我鞠躬! Alphonse:Gaston已經向我鞠躬!有時阿爾方斯:加斯東向我鞠躬!加斯頓:阿方斯向我鞠躬! – Sunny