Jurassic Park consists of a dinosaur museum and a park for safari riding. There
ID: 3811285 • Letter: J
Question
Jurassic Park consists of a dinosaur museum and a park for safari riding. There are k single-passenger cars and p passengers. Passengers wander around the museum for a while, then line up to take a ride in a safari car. When a car is available, it loads a passenger and rides around the park for a random amount of time. If the k cars are all out riding passengers around, then a passenger who wants to ride waits; if a car is ready to load but there are no waiting passengers, then the car waits. Solve this problem using semaphores. declare global variables here (e.g. semaphores, global counters etc) void Car Thread (int i) void Passenger Thread (int i) void main () {thread being(Passenger Thread(1), Passenger Thread(2), ...., Passenger Thread(P), Car Thread(1), Car Thread(2), ...., Car Thread (k));}Explanation / Answer
import Utilities.*;
import Synchronization.*;
class Passenger extends JurassicPark implements Runnable {
private int id = 0;
public Passenger(int id) { this.id = id; }
public void run() {
while (true) {
nap(1+(int)random(1000*wanderTime));
System.out.println("age="+agenger"+id+" wants to ride");
P(carAvail); V(carTaken); P(carFilled);
System.out.println("age="+agenger"+id+" taking a ride");
P(passengerReleased);
System.out.println("age="+agenger"+id+" finished riding");
}
}
}
class Car extends JurassicPark implements Runnable {
private int id = 0;
public Car(int id) { this.id = id; }
public void run() {
while (true) {
System.out.println("age="+ageid+" ready to load");
V(carAvail); P(carTaken); V(carFilled);
System.out.println("age="+ageid+" going on safari");
nap(1+(int)random(1000*rideTime));
System.out.println("age="+ageid+" has returned");
V(passengerReleased);
}
}
}
class JurassicPark extends MyObject {
static final int numPassengers = 10, numCars = 3;
static final int wanderTime = 5, rideTime = 4, runTime = 60;
static final CountingSemaphore carAvail = new CountingSemaphore(0);
static final CountingSemaphore carTaken = new CountingSemaphore(0);
static final CountingSemaphore carFilled = new CountingSemaphore(0);
static final CountingSemaphore passengerReleased = new CountingSemaphore(0);
public static void main(String[] args) {
for (int i = 0; i < numPassengers; i++)
new Thread(new Passenger(i)).start();
for (int i = 0; i < numCars; i++)
new Thread(new Car(i)).start();
nap(1000*runTime);
System.exit(0);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.