加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java死锁问题

发布时间:2020-12-14 16:31:17 所属栏目: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 v
任何人都可以解释为什么在这段代码中有一个僵局.谢谢
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)被锁定.等待锁释放.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读