gpt4 book ai didi

java - 关于Java死锁情况的问题

转载 作者:搜寻专家 更新时间:2023-10-30 21:15:11 25 4
gpt4 key购买 nike

我正在学习 Java 中的死锁,并且有来自 Sun 官方教程的示例代码:

Alphonse and Gaston are friends, and great believers in courtesy. A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a chance to return the bow. Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time.

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();
}
}

这是 Sun 的解释:

When Deadlock runs, it's extremely likely that both threads will block when they attempt to invoke bowBack. Neither block will ever end, because each thread is waiting for the other to exit bow.

我好像不太明白。当 alphonse.bow(gaston) 运行时, bow 方法被锁定。所以现在它会首先打印“Gaston has bowed to me!”。然后它将继续调用 bowBack,并锁定 bowBack。这怎么会导致死锁呢?我是否误解了调用同步方法时会发生什么?

如果有人能给我一个简单的解释,谢谢。

最佳答案

需要注意的重要一点是,锁定的不是方法,而是对象实例

当您调用 alphonse.bow(gaston) 时,它会尝试获取 alphonse 上的锁。获得锁后,它会打印一条消息,然后调用 gaston.bowBack(alphonse)。此时,它尝试获取 gaston 上的锁。获得锁后,它会打印一条消息,然后释放锁,最后释放 alphonse 上的锁。

在死锁中,锁的获取顺序使得任何一个线程都无法继续进行。

  • 线程 1:获取 alphonse 上的锁
  • 线程 2:获取 gaston 上的锁
  • 线程 1:打印消息
  • 线程 1:尝试获取 gaston 上的锁 - 不能,因为线程 2 已经拥有它。
  • 线程 2:打印消息
  • 线程 2:尝试获取 alphonse 上的锁 - 不能,因为线程 1 已经拥有它。

关于java - 关于Java死锁情况的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1562705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com