今天复习多线程的时候,在网上看到一段代码百思不得其解,望各位经过的学长学姐指点
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.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();
}
}
该回答引用ChatGPT
1、该代码中的死锁是由于双方互相持有对方对象的锁,从而造成无法继续执行的情况。具体来说,线程A获得了对象A的锁并执行了bow方法,然后它试图去调用对象B的bowBack方法,但是由于对象B被线程B持有并加锁了,所以线程A在执行到bower.bowBack(this)时会被阻塞,无法继续执行。同时,线程B也在等待对象A的锁,因此两个线程都在等待对方释放锁,造成了死锁。
2、System.out.format和System.out.println都可以输出内容到控制台,但是它们的格式化方式不同。System.out.format方法使用了类似于C语言中的printf函数的格式化字符串方式,可以将指定的参数根据格式化字符串的要求进行格式化输出。而System.out.println方法则直接输出指定的内容,不进行任何格式化操作。在这个例子中,如果将System.out.format换成System.out.println,那么输出的内容就不会按照预期进行格式化,而是直接输出。因此,这两种方法的使用应该根据实际需求进行选择。