嵌套类的同步

时间:2016-03-31 20:38:47

标签: java synchronization inner-classes

最近,我有机会查看来自Java文档here的材料。它包括以下代码;

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”上。请参考以下内容;

Locking and synchronization between outer and inner class methods?

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

感谢。

1 个答案:

答案 0 :(得分:0)

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)

- 死锁