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 synchronized (bowl) {
14 cup.put (2, "flour");
15 bowl.put (cup);
16 bowl.mix ();
17 }
18 }
19 }
20
21 public void makeOmelette () {
22 synchronized (cup) {
23 synchronized (bowl) {
24 bowl.put ("eggs");
25 bowl.mix ();
26 cup.put (bowl);
27 }
28 }
29 }
30
31 // sample main program using the kitchen
32 public static void main (String args[]) {
33 final Kitchen3 k = new Kitchen3 ();
34 class SwedishChef implements Runnable {
35 public void run () { k.makeCookies(); }
36 }
37 new Thread (new SwedishChef(), "Swedish Chef").start();
38 class JuliaChild implements Runnable {
39 public void run () { k.makeOmelette(); }
40 }
41 new Thread (new JuliaChild(), "Julia Child").start();
42 }
43 }