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