0
我在理解Oracle教程中的这个特定死锁示例时遇到了问题。 我认为我对死锁是什么有一个很好的想法(我已经看到了很多的例子,其中两个最终的对象锁创建,一个线程获得第一个和第二个),但这个似乎更复杂。棘手的死锁示例
为什么无法在不阻止程序的情况下调用bowBack()方法?如果方法同步于这个 - 如果我理解正确,这实际上是同步方法的工作方式 - 然后线程不共享资源,这会导致它们彼此等待。
是因为如果你试图在另一个同步方法中调用一个同步方法,你需要在这个外部方法中是“唯一的线程”?
从我收集,他们都进入弓()同时所有的罚款,直到bowBack()被调用......
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();
}
}