问题描述
我正在学习 Java 中的死锁,并且有来自 Sun 官方教程的示例代码:
I'm learning about deadlocks in Java, and there's this sample code from Sun's official tutorial:
阿尔方斯和加斯顿是朋友,而且礼节的大信徒.一个严格的礼貌规则是当你鞠躬时对朋友,你必须保持鞠躬直到你的朋友有机会归还弓.不幸的是,这规则不考虑两个朋友可能会鞠躬同时对彼此.
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();
}
}
这是孙的解释:
当死锁运行时,它非常可能两个线程都会阻塞当他们尝试调用 bowBack 时.两个区块都不会结束,因为每个线程都在等待另一个退出弓.
我似乎不太了解.当 alphonse.bow(gaston) 运行时,bow 方法被锁定.所以现在它会首先打印Gaston 向我鞠躬!".然后它会继续调用bowBack,并锁定bowBack.这怎么会导致死锁?我是否误解了调用同步方法时会发生什么?
I don't quite seem to follow. When alphonse.bow(gaston) runs, the bow method is locked. So now it'll first print "Gaston has bowed to me!". Then it'll go on and call bowBack, and locks bowBack as well. How can this cause a deadlock? Am I misunderstanding what happens when a synchronized method is called?
如果有人能给我一个简单的解释,谢谢.
If someone can give me a easy explanation, thanks.
推荐答案
需要注意的一点是,被锁定的不是方法,而是对象实例.
One important point to note is that it is not methods which are locked but object instances.
当您调用alphonse.bow(gaston)
时,它会尝试获取alphonse
的锁.一旦获得锁,它就会打印一条消息,然后调用 gaston.bowBack(alphonse)
.此时,它尝试获取 gaston
上的锁.获得锁后,它会打印一条消息,然后释放锁,最后释放对 alphonse
的锁.
When you call alphonse.bow(gaston)
, it tries to acquire the lock on alphonse
. Once it has the lock, it prints a message, then calls gaston.bowBack(alphonse)
. At this point, it tries to acquire the lock on gaston
. Once it has the lock, it prints a message, then releases the lock, and finally the lock on alphonse
is released.
在死锁中,锁的获取顺序使得任一线程都无法继续.
In deadlock, the locks are acquired in such an order that there's no way for either thread to proceed.
- 线程 1:获取
alphonse
的锁 - 线程 2:获取
gaston
的锁 - 线程 1:打印消息
- 线程 1:尝试获取
gaston
上的锁 - 不能,因为线程 2 已经拥有它. - 线程 2:打印消息
- 线程 2:尝试获取
alphonse
的锁 - 不能,因为线程 1 已经拥有它.
- Thread 1: acquires lock on
alphonse
- Thread 2: acquires lock on
gaston
- Thread 1: prints message
- Thread 1: tries to acquire lock on
gaston
- can't, because Thread 2 already has it. - Thread 2: prints message
- Thread 2: tries to acquire lock on
alphonse
- can't, because Thread 1 already has it.
这篇关于关于Java死锁情况的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!