读书人

线程死锁,该如何解决

发布时间: 2012-02-01 16:58:19 作者: rapoo

线程死锁

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方法里面的语句没打印出来

读书人网 >Java面试

热点推荐