Java 嵌套类的同步

Java 嵌套类的同步,java,synchronization,inner-classes,Java,Synchronization,Inner Classes,最近,我有机会回顾了Java文档中的资料。它包括以下代码 public class AnotherDeadlockCreator { class Friend { private final String name; public Friend(String name) { this.name = name; } public String getName() { return this.name; } p

最近,我有机会回顾了Java文档中的资料。它包括以下代码

public class AnotherDeadlockCreator {

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) {

    AnotherDeadlockCreator obj = new AnotherDeadlockCreator(); 

    final AnotherDeadlockCreator.Friend alphonse =
        obj.new Friend("Alphonse");

    final AnotherDeadlockCreator.Friend gaston =
            obj.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();
}
}

除此之外,我还读到嵌套类同步锁定在嵌套类的“this”上。请参考以下内容

现在我不明白的是——当我们将上述声明(关于嵌套类锁)应用于死锁代码时,这怎么可能导致死锁?我的意思是,如果线程访问不同对象上嵌套类的同步方法,死锁将如何发生?我错过了一些重要的东西吗

谢谢。

bow()和bowBack()在同一个对象上同步,该对象是Friend实例:alphonse和gaston

下面是死锁的一个示例:

alphonse.bow(gaston) is invoked at time T. (alphonse synch started)
gaston.bow(alphonse) is invoked at time T + 1. (gaston synch started)
gaston.bowBack(alphonse) is invoked at time T + 2. (gaston synch already taken...waiting)
alphonse.bowBack(gaston) is invoked at time T + 3.  (alphonse synch already taken...waiting)

--死锁。

当然可以。但这不应该造成这里的僵局。请看,通过两个线程调用的对象是不同的,因此它们具有不同的作用域,而不是共享的。因此,除非方法不是静态的,否则锁不应该停止并等待其他方法完成。