Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package assignment3;
- /**
- *
- * @author Zizo
- */
- public class Monitor {
- private enum State {
- THINKING, HUNGRY, EATING
- };
- private State[] state = new State[5];
- public Monitor() { //initial state
- for (int i = 0; i < 5; i++) {
- state[i] = State.THINKING;
- }
- }
- public synchronized void pickUp(int id) throws InterruptedException {
- state[id] = State.HUNGRY;
- System.out.println("Philosopher " + id + " is hungry.\n");
- System.out.flush();
- while (someNeighborIsEating(id)) {
- wait();
- }
- state[id] = State.EATING;
- System.out.println("Philosopher " + id + " is eating.\n");
- System.out.flush();
- }
- public synchronized void putDown(int id) {
- state[id] = State.THINKING;
- notifyAll();
- }
- private boolean someNeighborIsEating(int id) {
- if (state[(id + 1) % 5] == State.EATING || state[(id+4) % 5] == State.EATING) {
- return true;
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement