谁能解释一下为什么这段代码中会出现死锁。
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.bow(gaston);
,由于synchronized
关键字gaston.bow(alphonse);
,加斯顿现已锁定bower.bowBack(this);
方法调用中执行bow
。等待锁被释放。 bower.bowBack(this);
方法调用中执行bow
。等待锁被释放。 两个线程都互相等待释放锁。