Documentation

The Java™ Tutorials
Hide TOC
Deadlock死锁
Trail: Essential Java Classes
Lesson: Concurrency
Section: Liveness

Deadlock死锁

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. 死锁描述了两个或多个线程被永远阻塞,彼此等待的情况。Here's an example.这里有一个例子。

Alphonse and Gaston are friends, and great believers in courtesy. 阿尔方斯和加斯顿是朋友,非常相信礼貌。A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a chance to return the bow. 礼貌的一条严格规则是,当你向朋友鞠躬时,你必须保持鞠躬,直到你的朋友有机会回敬你。Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time. 不幸的是,这条规则没有考虑到两个朋友同时向对方鞠躬的可能性。This example application, Deadlock, models this possibility:此示例应用程序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();
    }
}

When Deadlock runs, it's extremely likely that both threads will block when they attempt to invoke bowBack. Deadlock运行时,两个线程在试图调用bowBack时极有可能都会阻塞。Neither block will ever end, because each thread is waiting for the other to exit bow.两个块都不会结束,因为每个线程都在等待另一个退出bow


Previous page: Liveness
Next page: Starvation and Livelock