import java.util.concurrent.Semaphore;


public class BarberSaloon3 extends Thread{

// *** for panel control configs ***

static final int nClients= 16; 
// nr of clients

static final int nChairs=5; 
// nr of chairs (barber chair also)

//e.g., 1 chair for barber + 3 for clients waiting 
// => 4 chairs permanently available

static final int minTimeHairCut=1500; 
// 15 minutes simulation

static final int variableTimeCut=1500; 
// 1500ms => 15 minutes

static final int maxTimeBetweenCuts=100; 
// short pause

// static final int maxTimeBetweenClients=500; 
// busy saloon => e.g.:5 minutes

static final int maxTimeBetweenClients=12000; 
//calmer saloon => e.g.: 120 minutes

static final int MaxClientAttemptsToCutHair=3;

static final int pauseBeforeJoins = 
	(int)(0.5*nClients*minTimeHairCut);

static int freeChairs= nChairs; 
// in the begin, all chairs are free (available)

static int nrClientsDeparted= 0;

static int nrHairCutsDone= 0;

	//3 semaphores are needed:


Semaphore semafMutex=new Semaphore(1);
	// semafMutex controls access to shared variable freeChairs

	// no Resource semaphore(4): it doesn't guarantee an order FIFO


Semaphore semafBarberReady = new Semaphore(0);
	// when Barber is ready for new client semafBarberReady:=1

Semaphore semafSaloonNotEmpty=new Semaphore(0); 
//begin: it's empty, false => 0
	// if saloon has clients semafSaloonNotEmpty:=1


public Semaphore getSemafMutex() { 
return semafMutex; }


public Semaphore getSemafSaloonNotEmpty() { 
return semafSaloonNotEmpty; }


public void setSemafSaloonNotEmpty(Semaphore semafSaloonNotEmpty) {
	this.semafSaloonNotEmpty = semafSaloonNotEmpty; }


public void setSemafMutex(Semaphore semafMutex) {
	this.semafMutex = semafMutex;}


public Semaphore getSemafBarberReady(){ 
	return semafBarberReady; }


public void setSemafBarberReady(Semaphore semafBarberReady) {
	this.semafBarberReady = semafBarberReady; }



// getters and setters


public static int getNrHairCutsDone() { 
return nrHairCutsDone; }


public static void setNrHairCutsDone(int nrHairCutsDone) {
	BarberSaloon3.nrHairCutsDone = nrHairCutsDone;}


public static int getnrClientsDeparted() { 
	return nrClientsDeparted;}


public static void setnrClientsDeparted(int nrClientsDeparted) {
	BarberSaloon3.nrClientsDeparted = nrClientsDeparted;}


public static int getFreeChairs() { 
	return freeChairs; }


public static void setFreeChairs(int freeChairs) {
		BarberSaloon3.freeChairs = freeChairs;}


private void displayIntro() {

	System.out.println(" *** Barber Saloon Simulation *** ");

	System.out.println("\n *** Parameters (panel of configuration) ***");

	System.out.println("\n nClients= " + nClients + 
", the nr total of clients ");

	System.out.println(" nChairs= " + nChairs + 
", the nr total of chairs (=> barber chair included).");

	System.out.println(" minTimeHairCut= " + 
(double) (minTimeHairCut/100.0) + 
", the minimum fixed time for hair cut (minutes).");

	System.out.println(" variableTimeCut= " + 
(double) (variableTimeCut/100.0) + 
", for max variable time in hair cut (minutes).");

	System.out.println(" maxTimeBetweenCuts= " + 
(double) (maxTimeBetweenCuts/100.0) + 
", for max time between hair cuts (minutes).");

	System.out.println(" maxTimeBetweenClients= " + 
(double) (maxTimeBetweenClients/100.0) + 
", for max arrival time between 2 clients (minutes).");

	System.out.println(" pauseBeforeJoins= " + 
(int)(pauseBeforeJoins/100.0) + 
", the pause main thread do before doing final joins (minutes).");

	System.out.println(" MaxClientAttemptsToCutHair= " + 
MaxClientAttemptsToCutHair + "
, the nr total of attempts to cut hair per client. ");

	System.out.println("\n\n *** Begin Simulation Barber Saloon (Sleeping Barber) *** \n");

};



public BarberSaloon3() {} //constructor


public static void main(String[] args) {
	BarberSaloon3 bs= new BarberSaloon3();bs.start();}


private void startClientThreads(Client[] c, Barber b) {

	for(int i=0;i< nClients;i++) {

		c[i]=new Client(i,b); c[i].start();

		try {Thread.sleep(
			(int)(Math.random()*maxTimeBetweenClients));}

		catch(InterruptedException e) {};
	}
}



private void clientsJoinedSummary(Client[] c) {

	try {Thread.sleep(pauseBeforeJoins );} 
	catch(Exception e) {};


	while (getnrClientsDeparted()<nClients)

		try {
			Thread.sleep((int)(maxTimeBetweenClients));} 
		catch(Exception e) {};

	try{System.out.println ("\n *** Summary of Clients (threads) finished  (joined) *** "); }
	catch(Exception e) {};


	for(int i=0;i< nClients;i++) {

		try { 
			c[i].join();

			if ((i%2)>0) System.out.print ("Client id: " + 
				i + " finished => thread joined. ");

			else System.out.print ("\n Client id: "+ i + 
				" finished => thread joined. ");

		} catch(InterruptedException e) {};
	}

	System.out.println ("\n\n **** End Simulation ****\n");

	System.out.println ("************************************************************************************************\n\n\n");

}


public void run() {

	displayIntro(); Barber b= new Barber(); b.start();

	Client [] c =new Client[ nClients]; // thread pool

	startClientThreads(c, b); clientsJoinedSummary(c);

	System.exit(1); //end program
}



public class Barber extends Thread{ // class Barber

private int timeCut=0;

private Client barberClient=null;


public int getTimeCut() { 
return timeCut; }


public void setTimeCut(int timeCut) { 
this.timeCut = timeCut;}


public Barber() {} //constructor


public Client getBarberClient() { 
return barberClient;}


public void setBarberClient(Client barberClient){
this.barberClient = barberClient;}


private void barberCutHair() {

	Client c= null; 

	int pause = (int)(Math.random()*maxTimeBetweenCuts);

	// try to get client

	if (getFreeChairs()==nChairs)

		System.out.print ("\n >>>> Barber maybe sleeps... saloon calm... Free chairs were " + nChairs + ". ");

		try {getSemafSaloonNotEmpty().acquire();} 
		catch(Exception e) {};

		while (c==null) { 
			// barber has already a client via semafSaloonNotEmpty => get it…

			try {

				c= getBarberClient();

				if ((c!= null) && (c.getTimeCut()>0) 
							&& (c.isCut()==false)) {

					System.out.print ("\n Barber begins hair cut of " +  						(double) c.getTimeCut()/100 + " minutes. ClientId: " 						+ c.getClientId() + " Freechairs = " + 
					getFreeChairs() + " Cut? " + c.isCut() + ".");

					Thread.sleep(c.getTimeCut());
				}

				else {
 
				System.out.print ("\n >>>> Barber Ready, but Client not Ready. + " + " Barber sleeps/pauses " + (double)(pause/100.0) + " minutes..."); 
			}


		}catch(Exception e) 
			// " Exception: " + e.getMessage() + 
			// {System.out.print(" Client was "+e.getMessage()+".");};

		try {Thread.sleep(pause);} 
		catch(InterruptedException e) {};

	}

}



public void run() { //begin: Barber gets ready

	try {
		getSemafBarberReady().release();}
	catch(Exception e) {};

	while(true) { barberCutHair(); }

	} // end run()


} // end inner class Barber







public class Client extends Thread{ // class Client

	
private int clientId;

private Barber b;

private boolean cut = false; 
	//begin: hair is not cut

private int timeCut; 
	// timeCut (ms). Used to simulates time of Cut in minutes


public int getClientId() { 
		return clientId;}


public void setClientId(int clientId) { 
	this.clientId = clientId;}


public Client(int i, Barber b) { 
clientId=i; this.b=b; }


public int getTimeCut() { 
	return timeCut; }


public void setTimeCut(int timeCut) {
	this.timeCut = timeCut; }


public Barber getB() { 
	return b; }


public void setB(Barber b) { 
	this.b = b; }


public void setCut(boolean cut) { 
	this.cut = cut; }


public boolean isCut() { 
return cut;}


private void clientGetHairCut() {

	setTimeCut((int)(minTimeHairCut+ Math.random() * variableTimeCut));

	// random timecut; but it's the same timecut 
	// for client and for the barber

	try { b.setBarberClient(this);Thread.sleep((int)(Math.random()*maxTimeBetweenCuts));}

	catch(Exception e){};

	System.out.print ("\n Client id="+getClientId() + 
		" begins hair cut of " + 
		(double) (getTimeCut()/100.0) + " minutes.");

	try { 
		Thread.sleep(getTimeCut());} 
	catch(InterruptedException e) {};

	try {
		getSemafMutex().acquire();} 
	catch(Exception e) {};

	setFreeChairs(getFreeChairs()+1); 
	//freeChairs++;

	this.cut= true;

 	BarberSaloon3.setNrHairCutsDone(
		BarberSaloon3.getNrHairCutsDone() + 1);

	System.out.print ("\n Client id=" + getClientId() + 
	" ends hair cut of " + 	(double)(getTimeCut()/100.0) + 
	" minutes. Now: Freechairs = " + getFreeChairs() + 
	". Now: Nr Hair Cuts Done = " + 
	BarberSaloon3.getNrHairCutsDone()+".");

	try {
		getSemafMutex().release();} 
	catch(Exception e) {};

}


private void displayTextClientArrives(int count) {

	String s; 
	s = "\n Client id= " + getClientId() + " arrives";

	if (count==1) { 
		s+="."; } 
	else { 
		s+=" again."; }

	System.out.print (s);

}


public void run() {

	int trials=1; 
	// nr of attempts of client in order to get hair cut

	while ((isCut()==false) && 
		(trials<=MaxClientAttemptsToCutHair)) {

		try {

			displayTextClientArrives(trials);

			//semafMutex: to control access to nr of free chairs

			try { getSemafMutex().acquire(); } 
			catch(Exception e) {};

			if (freeChairs> 0) {

				setFreeChairs(getFreeChairs()-1); 
				//freeChairs--;
		
				try {
					getSemafSaloonNotEmpty().release();} 
				catch(Exception e) {};

				System.out.print (" Client id=" + 
				getClientId() + " seats and waits.  Freechairs = " +  					getFreeChairs() + ". Trials:" + trials + ".");

				try {getSemafMutex().release();} 
				catch(Exception e) {};

				try {getSemafBarberReady().acquire();} 
				catch(Exception e) {};

				clientGetHairCut(); 
				// hair cut; it also increases nr of free chairs

				// syncro: next client only gets hair cut 
				// after this client leaves barber chair

				try {getSemafBarberReady().release();} 
				catch(Exception e) {};

			}

			else {// assumption: client comes a bit later, 
				// up to MaxClientAttemptsToCutHair times…

				try {getSemafMutex().release();} 
				catch(Exception e) {};

				System.out.println (" Saloon full. Client id=" + 							getClientId() + 
					" comes maybe later. Freechairs = " 
					+ getFreeChairs() + ". Trials: "+trials+".");

				if(trials<MaxClientAttemptsToCutHair)

				try {
					Thread.sleep((int) 												( Math.random()*2*minTimeHairCut) );}

				catch(Exception e) {};

			}

			trials++;

			}

		catch(Exception e) {};

	}// end while

	setnrClientsDeparted(getnrClientsDeparted()+1);

	System.out.println ("\n *** Client id=" + getClientId() + 
		" departed. Freechairs = " + 	getFreeChairs() + ". Hair cut?" + 
		isCut() + ". Trials? " + (int) (trials-1) + ". Clients departed: " + 			getnrClientsDeparted() + " *** ");

}// end run()


}// end inner class Client


}// end BarberSaloon3 class