考虑以下:
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("\n%S: %S has bowed to me!" , this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("\n%S: %S has bowed back to me!", this.name, bower.getName());
}
}
public static void main(String[] args) {
final Friend alf = new Friend("Alf");
final Friend arian = new Friend("Arian");
// Thread 1
new Thread(new Runnable() {
public void run(){ alf.bow(arian);}}).start();
//Thread 2
new Thread(new Runnable() {
public void run(){ arian.bow(alf);}}).start();
}
}
输出是
ALF:阿里安已经向我鞠躬了!阿里安:阿尔夫已经向我鞠躬了!
LOCK情况……
当线程 1 运行时,它需要锁定对象 Friend。紧接着线程 2 需要锁定第二个对象。现在方法bow 被线程 1 锁定,因此打印“ALF: ARIAN has bowed to me!”。线程 2 怎么进入bow也不能进入* bowBack * ??
问候 B。