Java死锁问题
发布时间:2020-07-16 09:00:44 所属栏目:Java 来源:互联网
导读:任何人都可以解释为什么在这段代码中有一个僵局.谢谢 public class Deadlock { static class Friend { private final String name; public Friend(String name) { this.name = name; } publ
|
任何人都可以解释为什么在这段代码中有一个僵局.谢谢 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",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();
}
}
解决方法以下是它可能被执行的方式.>输入alphonse.bow(gaston);由于synchronized关键字,alphonse现在被锁定 两个线程等待彼此释放锁定. (编辑:鄂州站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
