当前位置: 代码迷 >> Java面试 >> 线程死锁,该如何解决
  详细解决方案

线程死锁,该如何解决

热度:91   发布时间:2016-04-17 19:41:38.0
线程死锁
Java code
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();    }}


这段代码会造成死锁现象吗?

------解决方案--------------------
回复lz 不会, 给分吧。
------解决方案--------------------
会造成死锁的 执行到这句bower.bowBack(this);方法时会发现根本进不去,因为bow方法没执行完,对象锁标志没释放,所以就一直卡在这,不然为啥bowBack方法里面的语句没打印出来
  相关解决方案