本文介绍了Java死锁问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何人都可以解释为什么这段代码中存在死锁。谢谢
can anyone explain me why there is a deadlock in this code.Thanks
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();
}
}
推荐答案
这里是它可能会被执行。
Here's how it probably will be executed.
- 输入
alphonse.bow(gaston);
,alphonse现已锁定,因为已同步
关键字 - 输入
gaston.bow(alphonse);
,gaston现已锁定 - 无法从第一个<$ c $执行
bower.bowBack(this);
c> bow 方法调用因为gaston(bower)被锁定。等待锁被释放。 - 无法从第二个
执行
方法调用因为alphonse(bower)被锁定。等待锁被释放。bower.bowBack(this);
bow
- Enter
alphonse.bow(gaston);
, alphonse is now locked due tosynchronized
keyword - Enter
gaston.bow(alphonse);
, gaston is now locked - Can't execute
bower.bowBack(this);
from firstbow
method call because gaston (bower) is locked. Wait for lock to be released. - Can't execute
bower.bowBack(this);
from secondbow
method call because alphonse (bower) is locked. Wait for lock to be released.
两个线程互相等待释放锁定。
Both threads wait for each other to release lock.
这篇关于Java死锁问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!