首先,这是一个示例:
public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s has bowed back to me!%n",
this.name, bower.getName());
}
}
public static void main(String[] args) {
final Friend alphonse = new Friend("Alphonse");
final Friend gaston = new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
我不明白阻塞是如何发生的。主函数启动两个线程,每个线程都开始自己的弓。
“同步”到底是什么块?为同一个对象运行相同的函数(正如我最初认为的那样)?同一类的所有对象都具有相同的功能?同一个对象的所有同步函数?同一类的所有对象的所有同步函数?
帮帮我。