任何人都可以解释为什么在这段代码中有一个僵局.谢谢

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

解决方法

以下是它可能被执行的方式.

>输入alphonse.bow(gaston);由于synchronized关键字,alphonse现在被锁定
>输入gaston.bow(alphonse),gaston现在被锁定了
>无法执行bower.bowBack(this);从第一个弓方法调用,因为gaston(bower)被锁定.等待锁释放.
>无法执行bower.bowBack(this);从第二弓方法调用,因为alphonse(bower)被锁定.等待锁释放.

两个线程等待彼此释放锁定.

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。