【发布时间】:2019-09-11 08:08:33
【问题描述】:
我正在关注有关并发的 oracle 文档,在deadlock section 中,他们使用了以下示例。问题是我不太明白为什么会导致死锁。
在我看来,这就是我猜它正在发生的事情:
- Alphonse 向 Gaston 鞠躬并获得了
bow方法的锁定 - Alphonse 离开
bow方法并进入bowBack,释放第一个锁并获取第二个锁。 - 加斯顿重复这个过程
但我一定是错的,因为如果你运行代码,它会导致死锁......我在这里错过了什么?
非常感谢!
public class Deadlock
{
public static void main(String[] args)
{
final Friend alphonse = new Friend("Alphonse");
final Friend gaston = new Friend("Gaston");
new Thread(() -> alphonse.bow(gaston)).start();
new Thread(() -> gaston.bow(alphonse)).start();
}
static class Friend
{
private final String name;
Friend(final String name)
{
this.name = name;
}
String getName()
{
return name;
}
synchronized void bow(final Friend bower)
{
System.out.printf("%s: %s has bowed to me!%n", this.name, bower.getName());
bower.bowBack(this);
}
synchronized void bowBack(final Friend bower)
{
System.out.printf("%s: %s has bowed back to me!%n", this.name, bower.getName());
}
}
}
【问题讨论】:
-
这是正确的@michalk,与这里的问题相同,我必须将我的问题标记为重复还是删除它?非常感谢!
标签: java concurrency deadlock synchronized