Professional Documents
Culture Documents
Java Code
Java Code
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Semaphore;
/*
* we create the semaphores.
*/
//Semaphore to signal person is out of elevator
public static Semaphore persons = new Semaphore(0,true);
//Semaphore to signal person in elevator
public static Semaphore elevator = new Semaphore(0,true);
//Semaphore to control access to elevator
public static Semaphore accessElevator = new Semaphore(0,true);
/*
* we create the integer iD which is a unique ID number for every
* person and a boolean notRide which is used in the Person waiting
* loop. Also a randomized floor they want to go to
*/
int iD;
int floor;
boolean notRide = true;
public Person(int i) {
iD = i;
Random rand = new Random();
floor = rand.nextInt(9) + 2;
}
public Elevator() {
}
int num=0;
for(int p: hash){ //cycles through hash set, with p being the floor number
//num is important to be able to know how how many signals elevator should
signal
//on each floor to people waiting to get off, i.e. counts how many
duplicates
//in numbers list
num=Collections.frequency(numbers, p);
//signals num amount of times for people to get off according to person's
floor's semaphore
for(int i=0; i<num; i++)
sem[p-2].release(); //p-2 because array starts at index 0 but floor
starts at 2
try {
for(int i=0; i<num; i++) //once people get off on their respective
floor, must signal
persons.acquire(); //so elevator can continue and be in sync
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Elevator door closes");
}
System.out.println();
//list.clear();
numbers.clear();
hash.clear();
}
}
}
/* MAIN METHOD */
while(true){