【发布时间】:2015-02-02 11:48:36
【问题描述】:
该示例说明了死锁是如何发生的。有一点我不明白,就是当第一个调用实例alphone的方法bow的thead即将执行gaston.bowbBack(this)时,线程是否会释放锁并获取实例gaston的锁? ,假设它不属于第二个线程?或者它会同时持有两个锁,直到方法的所有代码都被完全执行?还有一个问题,有没有办法检查线程是否持有锁?
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 个锁。链接帖子上选择的答案应该说明会发生什么。