首页 新闻 会员 周边 捐助

Java- 请问如何使这段代码死锁?

0
悬赏园豆:30 [已解决问题] 解决于 2019-08-06 16:05

public class MicroBlongNode {

public static void main(String[] args) {
    final MicroBlongNode local = new MicroBlongNode("localhost:8888");
    final MicroBlongNode other = new MicroBlongNode("127.0.0.1:8988");
    final String first = "1";
    final String second = "2";

    new Thread(() -> local.propagate(first, other)).start();
    new Thread(() -> other.propagate(second,local)).start();
}

private final String ident;

public MicroBlongNode(String ident) {
    this.ident = ident;
}

public String getIdent() {
    return ident;
}

public synchronized void propagate(String upd, MicroBlongNode backup) {
    System.out.println(ident + ":recvd " + upd + "; backup:" + backup.getIdent());
    this.confirmUpdate(this, upd);
}

public synchronized void confirmUpdate(MicroBlongNode other, String upd) {
    System.out.println(ident + ":recvd confrim" + upd + "; from:" + other.getIdent());
}

}

草莓罐头的主页 草莓罐头 | 菜鸟二级 | 园豆:204
提问于:2019-08-06 15:18
< >
分享
最佳答案
0

我自己想明白了,谢谢各位浏览,
在方法上加锁,锁着的是当前对象,这样永远不会死锁的,但是调用另一个方法时加上这句话
synchronized (backup) {
this.confirmUpdate(this, upd);
}
当我在propagate()方法中,锁住另一个MicroBlongNode 对象时,就可能出现死锁

草莓罐头 | 菜鸟二级 |园豆:204 | 2019-08-06 16:04
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册