Deadlock

死锁描述了一种情况,其中两个或多个线程永远被阻塞,互相 await。这是一个例子。

阿方斯(Alphonse)和加斯顿(Gaston)是朋友,也是礼貌的忠实信徒。严格的礼貌规则是当您向朋友鞠躬时,您必须保持鞠躬,直到您的朋友有机会归还弓箭为止。不幸的是,该规则不能解决两个朋友可能同时鞠躬的可能性。此示例应用程序Deadlock为这种可能性建模:

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运行时,两个线程极有可能在try调用bowBack时阻塞。两个块都不会结束,因为每个线程都在 await 另一个退出bow