The Java Program: Kitchen3.java

  1 // Kitchen3.java -- lock hierarch avoids deadlock
  2 
  3 class Kitchen3 {
  4 
  5    //  In this kitchen only one measuring cup and one mixing bowl
  6    static MeasuringCup cup = new MeasuringCup();
  7    static MixingBowl  bowl = new MixingBowl();
  8 
  9    // lock hierarchy:  first cup, then bowl
 10 
 11    public void makeCookies () {
 12       synchronized (cup) {
 13          cup.put (2, "flour");
 14          synchronized (bowl) {
 15             bowl.put (cup);
 16             bowl.mix ();
 17          }
 18       }
 19       // Use oven
 20    }
 21 
 22    public void makeOmelette () {
 23       synchronized (cup) {
 24          synchronized (bowl) {
 25             bowl.put ("eggs");
 26             bowl.mix ();
 27             cup.put (bowl);
 28          }
 29       }
 30       // Use range
 31    }
 32 
 33    // sample main program using the kitchen
 34    public static void main (String args[]) {
 35       final Kitchen3 k = new Kitchen3 ();
 36       class SwedishChef implements Runnable {
 37          public void run () { k.makeCookies(); }
 38       }
 39       new Thread (new SwedishChef(), "Swedish Chef").start();
 40       class JuliaChild implements Runnable {
 41          public void run () { k.makeOmelette(); }
 42       }
 43       new Thread (new JuliaChild(), "Julia Child").start();
 44    }
 45 }