Advertisement
ahmad_zizo

Monitor

May 25th, 2015
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package assignment3;
  7.  
  8. /**
  9.  *
  10.  * @author Zizo
  11.  */
  12. public class Monitor {
  13.  
  14.     private enum State {
  15.  
  16.         THINKING, HUNGRY, EATING
  17.     };
  18.     private State[] state = new State[5];
  19.  
  20.     public Monitor() { //initial state
  21.         for (int i = 0; i < 5; i++) {
  22.             state[i] = State.THINKING;
  23.         }
  24.     }
  25.  
  26.     public synchronized void pickUp(int id) throws InterruptedException {
  27.         state[id] = State.HUNGRY;
  28.         System.out.println("Philosopher " + id + " is hungry.\n");
  29.         System.out.flush();
  30.         while (someNeighborIsEating(id)) {
  31.             wait();
  32.         }
  33.         state[id] = State.EATING;
  34.         System.out.println("Philosopher " + id + " is eating.\n");
  35.         System.out.flush();
  36.     }
  37.  
  38.     public synchronized void putDown(int id) {
  39.         state[id] = State.THINKING;
  40.         notifyAll();
  41.     }
  42.    
  43.     private boolean someNeighborIsEating(int id) {
  44.         if (state[(id + 1) % 5] == State.EATING || state[(id+4) % 5] == State.EATING) {
  45.             return true;
  46.         }
  47.         return false;
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement