首页 文章

一个棘手的死锁示例[重复]

提问于
浏览
0

这个问题在这里已有答案:

我在从Oracle教程中理解这个特定的死锁示例时遇到了问题 . 我想我对死锁是一个很好的想法(我已经看到很多例子,其中创建了两个最终的Object锁,一个线程获得了第一个,第二个获得了另一个),但是这个看起来更复杂 .

为什么不能在不阻塞程序的情况下调用bowBack()方法呢?如果这些方法是同步的 - 如果我理解正确,这实际上是同步方法的工作方式 - 那么线程不会共享一个会导致它们彼此等待的资源 .

是因为如果你尝试在另一个同步方法中调用synchronized方法,你需要成为这个外部方法中的“唯一线程”吗?

从我收集到的,他们都同时进入bow()并且一切都很好,直到bowBack()被调用...

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();
    }
}

1 回答

  • 1

    这里的重要部分是参数/参数也被锁定,并且在另一个对象上调用bowback方法,而不是在 this 上 .

    如果该行反而读取 this.bowback() 一切都会好的,但它是 anotherObject.bowback() ,并且该对象尝试自身同步,但已被另一个线程锁定 .

相关问题