请问有人能解释为什么以下代码会导致死锁吗?
我的理解是当阿尔方斯(线程)运行时,它会因为调用bow()方法而获得friend对象的锁,但是为什么加斯顿(另一个线程)能够在阿尔方斯还没有完成/释放friend对象的锁的情况下获得同一friend对象的锁呢?
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.println("invoked by " + name);
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
System.out.printf("finished by " + name);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
System.out.println("exiting bowBack()");
}
}
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();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
static final
字段进行同步,这将使得等待所有类的实例。 - Luiggi Mendozapublic synchronized void yourMethod
。 - Luiggi Mendoza