
// Barber.java
// Andrew Davison, ad@coe.psu.ac.th, May 2023

/* The Sleeping barber problem:
  https://en.wikipedia.org/wiki/Sleeping_barber_problem

  When a barber is free, he checks the waiting 
  room for alerts, and begins cutting the hair of the next 
  customer in the queue. If there are no alerts, he goes to 
  sleep until woken by an alert.

  Usage:
    > compile.bat Barber.java

    Part of the application made up of:
       * BarberShop.java
       * Barber.java
       * WaitingRoom.java
       * Customer.java
*/


import org.jspace.*;


public class Barber implements Runnable
{
  private int id;
  private WaitingRoom room;
  private PrintAreas pas;
  private Space space;

  public Barber(int id, WaitingRoom wr, PrintAreas pas, Space s)
  {
    this.id = id;
    room = wr;
    this.pas = pas;
    space = s;
    pas.setTitle(id, "Barber-"+id);
  }


  public void run()
  {
    try {
      while (true) {
        space.get( new ActualField("ALERT"));
        pas.println(id, "Woken by an alert; look for a customer");
        int custID = room.getCustomer(id);
             /* the waiting room selects the next customer
                for the barber */
        if (custID != -1) {
          pas.println(id, "Cut customer " + custID + " hair");
          SpaceUtils.pause(4000);  // take some time to finish
        }
        else
          pas.println(id, "No customer");
      }
    }
    catch (InterruptedException e) 
    {  System.out.println("Barber " + id + " error: " + e);  }
  } /* run */

}  // end of Barber class
