Question About Deadlock Situation in Java

前端 未结 6 2271
鱼传尺愫
鱼传尺愫 2020-12-08 12:06

I\'m learning about deadlocks in Java, and there\'s this sample code from Sun\'s official tutorial:

Alphonse and Gaston are friends, and great belie

6条回答
  •  暖寄归人
    2020-12-08 12:32

    alphonse and gaston are two different objects. Each object has an intrinsic monitor (lock) that is associated with it.

    It could happen like this:

    alphonse is created. His object monitor is 1.

    gaston is created. His object monitor is 2.

    alphonse.bow(gaston); alphonse now owns lock #1

    gaston.bow(alphonse); gaston now owns lock #2

    alphonse calls bowBack on gaston and is waiting for lock #2 gaston calls bowBack on alphonse and is waiting for lock #1

    Make sense? Using the synchronized keyword locks that instances monitor for the duration of the method. The example could be rewritten as follows:

    public class Deadlock {
        static class Friend {
            private final String name;
            public Friend(String name) {
                this.name = name;
            }
            public String getName() {
                return this.name;
            }
            public void bow(Friend bower) {
                synchronized(this) {            
                            System.out.format("%s: %s has bowed to me!%n", 
                        this.name, bower.getName());
                            bower.bowBack(this);
                }
            }
            public void bowBack(Friend bower) {
                synchronized(this) {
                            System.out.format("%s: %s has bowed back to me!%n",
                        this.name, bower.getName());
                }
            }
        }
    }
    

提交回复
热议问题