在这段代码中死锁发生在哪里?Java


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

在线教程说

当Deadlock运行时,两个线程在试图调用bowBack时极有可能会阻塞。两个块都不会结束,因为每个线程都在等待另一个线程退出。

但是我没有看到任何相互依赖。谁能解释一下僵局在哪里?

这是一个经典的死锁,2个线程+ 2个锁。

1)线程1锁定alphonse并移动到锁定gaston

2)线程2锁定gaston并移动到锁定alphonse

3)线程1到达gaston,但被线程2和线程1阻塞

4)线程2到达alphonse,但它被线程1锁定并阻塞

在这里添加延迟以增加概率

public synchronized void bow(Friend bower)  {
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
...

最新更新