这是我的示例线程代码。什么是正确的逻辑输出,我得到的示例线程代码
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