为什么这个例子来自Java的文档,导致死锁?

时间:2014-07-09 12:22:54

标签: java thread-safety deadlock

我发现了这个可能导致Oracle's official Java site.

死锁的代码示例
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();
    }
}

有人可以解释为什么它可能导致死锁吗?

当第一个朋友(" Alphonse")为run时,它会执行bow并在另一个朋友上调用bowBack。在发生这种情况的某个地方,第二个朋友(" Gaston")运行,它执行自己的bow版本并在Alphonse上调用bowBack。那么哪里有僵局?他们都在调用自己的方法版本。

0 个答案:

没有答案