今天复习多线程的时候,看到网上有这么一段代码,百思不得其解。望各位学长学姐指点
疑问1、为何调用bower.bowBack(this)无反应
疑问2、为何将System.out.format换成System.out.println就变成了循环重复执行bow、bowBack方法
package cn.edu.jyu.secure;
public class DeadLock {
static class Friend {
private final String name;
Friend(String name) {
this.name = name;
}
String getName() {
return this.name;
}
synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me=====!%n",
this.name, bower.getName());
bower.bowBack(this);
}
synchronized void bowBack(Friend bower) {
System.out.println("进来了");
System.out.format("%s: %s"
+ " has bowed back to me----!%n",
this.name, bower.getName());
bower.bow(this);
}
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(() -> alphonse.bow(gaston)).start();
new Thread(() -> gaston.bow(alphonse)).start();
}
}