這是我的示例線程代碼。什麼是正確的邏輯輸出,我得到的示例線程代碼
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();
}
}
請幫我弄清楚上面這段代碼顯示的行爲背後的正確原因。
由於刪除
synchronize(this)
或synchronize(bower)
澄清我的困惑。 +1。 – Sadique