Skip to content

Instantly share code, notes, and snippets.

@pubudu91
Created September 27, 2016 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pubudu91/4f1237c4a6f562ceec121ffae58b3f91 to your computer and use it in GitHub Desktop.
Save pubudu91/4f1237c4a6f562ceec121ffae58b3f91 to your computer and use it in GitHub Desktop.
public class Q4 {
public final static int PIZZA_SLICE = 1; // One piece of pizza
public final static int PIZZA_REORDER = 0; // Pizza finished. Signals to reorder
public final static int PIZZA_FINISHED = -1; // Pizza finished
public static void main(String[] args) {
Plate pizzaPlate = new Plate(new Pizza()); // Create a plate to hold the pizza
Runnable[] students = new Runnable[15];
// Runnable implementation for a pizza order
Runnable pizzaOrder = () -> {
synchronized (pizzaPlate) {
if (pizzaPlate.isEmpty()) {
pizzaPlate.addNewPizza(new Pizza());
System.out.println("Kamal brought a new pizza");
pizzaPlate.notifyAll();
}
}
};
for (int i = 0; i < students.length; i++) {
students[i] = () -> {
while (true) {
int gotPizza;
synchronized (pizzaPlate) {
gotPizza = pizzaPlate.takePizzaSlice(); // Try to take a slice of pizza
if (gotPizza == PIZZA_REORDER) {
System.out.println("Pizza finished. " +
Thread.currentThread().getName() + " is placing a new order.");
new Thread(pizzaOrder).start(); // Order a new pizza
try {
pizzaPlate.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else if (gotPizza == PIZZA_FINISHED) {
try {
System.out.println("No pizza. " +
Thread.currentThread().getName() + " is going to sleep.");
pizzaPlate.wait(); // If there is no pizza, go sleep until there is a new pizza
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// If you get a slice of pizza, go on ahead, eating & studying
if (gotPizza == PIZZA_SLICE) {
System.out.println(Thread.currentThread().getName() + " is eating pizza & studying");
study();
}
}
};
new Thread(students[i], "Student #" + (i + 1)).start();
}
}
public static void study() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Plate {
private Pizza pizza;
public Plate(Pizza pizza) {
this.pizza = pizza;
}
public int takePizzaSlice() {
pizza.slices--;
if (pizza.slices >= 0)
return 1;
else if (pizza.slices == -1)
return 0;
else
return -1;
}
// Replace the current pizza with a new one
public void addNewPizza(Pizza pizza) {
this.pizza = pizza;
}
public boolean isEmpty() {
return pizza == null || pizza.slices <= 0;
}
}
class Pizza {
int slices = 8;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment