Im trying to understand how implement Dining Savages using monitors. I have three classes, and im using the kitchen class to act as the monitor for when the pot is empty or not.
For some reason i keep getting a null pointer exception at thread two in my example below.
class Kitchen {
Kitchen k;
int c;
boolean empty;
Cook chef;
Kitchen() {
this.c = 0;
this.empty = true;
chef = new Cook(k);
}
synchronized void putServingsInPot(int servings) {
if (empty) {
this.c = servings;
}
empty = false;
notify();
}
synchronized void getServingsFromPot() {
while (empty) {
try {
System.out.println("Bout to wait");
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("In Catch");
e.printStackTrace();
}if (c == 0) {
empty = true;
chef.run();
}else if(c > 0 && empty == false){
c--;
}
}
}
}
class Savage extends Thread {
Kitchen k;
Savage(Kitchen k) {
this.k = k;
}
public void run() {
while (true) {
k.getServingsFromPot();
try {Thread.sleep(500); // eat
} catch (Exception e) { return;}
}
}
}
class Cook extends Thread {
Kitchen k;
Cook(Kitchen k) {
this.k = k;
}
public void run() {
while (true) {
try {Thread.sleep(500); // sleep
} catch (Exception e) {return;}
k.putServingsInPot(10); // 10 servings
}
}
}
public class main {
public static void main(String Args[]) {
// Kitchen testing
Kitchen k = new Kitchen();
Cook c = new Cook(k);
c.start();
Savage sc[] = new Savage[9];
for (int i = 0; i < 9; i++) {
sc[i] = new Savage(k);
sc[i].start();
}
try {
Thread.sleep(5000);
} catch (Exception e) {
}
for (int i = 0; i < 9; i++) {
sc[i].interrupt();
}
c.interrupt();
System.out.println("Done\n");
}
}
Is it possible to synchronized these events without using a semaphore within the monitor ?