死锁(Deadlock描述了一种情况,其中两个或多个线程永远被阻塞,互相等待。这有一个例子。
    Alphonse和Gaston是朋友,也是礼貌的忠实信徒。严格的礼貌规则是当您向朋友鞠躬时,您必须保持鞠躬,直到您的朋友有机会结束鞠躬为止。不幸的是,该规则不能解决两个朋友可能同时鞠躬的可能性。示例应用程序Deadlock对这种可能性进行建模:

    1. public class Deadlock {
    2. static class Friend {
    3. private final String name;
    4. public Friend(String name) {
    5. this.name = name;
    6. }
    7. public String getName() {
    8. return this.name;
    9. }
    10. public synchronized void bow(Friend bower) {
    11. System.out.format("%s: %s"
    12. + " has bowed to me!%n",
    13. this.name, bower.getName());
    14. bower.bowBack(this);
    15. }
    16. public synchronized void bowBack(Friend bower) {
    17. System.out.format("%s: %s"
    18. + " has bowed back to me!%n",
    19. this.name, bower.getName());
    20. }
    21. }
    22. public static void main(String[] args) {
    23. final Friend alphonse =
    24. new Friend("Alphonse");
    25. final Friend gaston =
    26. new Friend("Gaston");
    27. new Thread(new Runnable() {
    28. public void run() { alphonse.bow(gaston); }
    29. }).start();
    30. new Thread(new Runnable() {
    31. public void run() { gaston.bow(alphonse); }
    32. }).start();
    33. }
    34. }

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