今天复习多线程的时候,看到网上有这么一段代码,百思不得其解。望各位学长学姐指点
疑问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();
}
}
代码示例展示了Java中可能出现死锁的情况,当两个线程互相等待对方释放资源时,导致程序无法继续执行。在原始代码中,`bowBack`方法使用`System.out.println`时会出现循环调用,而`System.out.format`则不会,这可能与println的缓冲行为有关。文章主要探讨了这个问题并寻求解答。
171万+

被折叠的 条评论
为什么被折叠?



