该示例说明了死锁是如何发生的。有一件事我不明白,那就是当第一个调用实例alphone的方法bow的addad即将执行gaston.bowbBack(this)时,线程是否会释放锁并获取实例gaston的锁if ,假设它不属于第二个线程?或者它会同时持有两个锁,直到方法的所有代码完全执行?还有一个问题,有什么办法来检查线程是否持有锁?一个线程可以同时持有两个锁吗?
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();
}
}
好随时我看到这个例子出现我开始寻找关闭这个作为重复,我们已经在这一个了很多。是的,没有理由一次线程不能超过1个锁。链接的帖子上的选定答案应该明确发生了什么。 – 2014-12-04 14:47:06