Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class Floor {
enum State { NO_ONE_WAITING, PASSENGERS_WAITING, LOADING }
private int passengersWaiting = 0;
private State state = State.NO_ONE_WAITING;
synchronized public void waitForElevator(String msg) {
if (state == State.LOADING) {
try {
wait();
} catch (InterruptedException ex) {
}
}
passengersWaiting++;
System.out.println(msg);
if (state == State.NO_ONE_WAITING) {
this.state = State.PASSENGERS_WAITING;
notifyAll();
}
}
synchronized public void getOnOffElevator(String msg) {
if (state != State.LOADING) {
try {
wait();
} catch (InterruptedException ex) { }
}
passengersWaiting--;
System.out.println(msg);
if (passengersWaiting == 0) {
this.state = State.NO_ONE_WAITING;
notifyAll();
}
}
synchronized public void elevatorArrives(String msg) {
if (state == State.LOADING) {
try {
wait();
} catch (InterruptedException ex) { }
}
System.out.println(msg);
if (state == State.PASSENGERS_WAITING) {
this.state = State.LOADING;
} else {
this.state = State.NO_ONE_WAITING;
}
notifyAll();
}
synchronized public void elevatorLeaves(String msg) {
if (state != State.NO_ONE_WAITING) {
try {
wait();
} catch (InterruptedException ex) { }
}
System.out.println(msg);
}
}
import scala.actors._
import scala.actors.Actor._
class Floor(floorNum: int) extends Actor {
private var passengersWaitingToGetOn = List[(Passenger, Floor)]()
private var passengersWaitingToGetOff = List[Passenger]()
def act() = {
loop {
react {
case (passenger: Passenger, floor: Floor) =>
passengersWaitingToGetOn = (passenger, floor) :: passengersWaitingToGetOn
println(passenger + " waiting for elevator at " + this)
case (passenger: Passenger) =>
passengersWaitingToGetOff = passenger :: passengersWaitingToGetOff
println(passenger + " on elevator to " + this)
case (elevator: Elevator) =>
for (passenger <- passengersWaitingToGetOff) {
println(passenger + " getting off at " + this)
}
passengersWaitingToGetOff = List[Passenger]()
for ((passenger, floor) <- passengersWaitingToGetOn) {
println(passenger + " getting on at " + this)
floor ! passenger
}
passengersWaitingToGetOn = List[(Passenger, Floor)]()
elevator ! "loaded"
case msg =>
println("Unhandled message: " + msg)
}
}
}
override def toString() = "Floor " + floorNum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.