Deadlock - how does it happen in this example?

Viewed 3636

can anyone explain:

  1. why do we get a deadlock?
  2. how can Gaston enter function bow before Alphonse exit that function? (it should return from function bowBack() in order to exit the function bow() - or)?

This is the output I get - and then program is stuck!

Alphonse: Gaston has bowed to me!

Gaston: Alphonse has bowed to me!

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();
    }
} 
4 Answers
Related