There are two queues of children waiting to use a roundabout in a playground – one is facing it from the north, one from the south. Children may only enter the roundabout from the front of either queue and may only enter if there is a space available (only one child may use each segment at a time). Once on the roundabout they use it for a random period of time, then leave, either to the east or west, at random. They then play elsewhere for a random period and, after that, re-enter a north/south queue at random, and so on ad infinitum. The roundabout rotates clockwise and a queuing child will always use the first space that comes along… Write a program using java semaphores to synchronise access to the shared roundabout object by set of processes that represent the children.
Here is what I have done so far, and don't know what to do next. What do I do in Main class?
import java.util.Random;
public class Child extends Thread {
private Random random;
private int which;
private int number;
public Child(int number) {
this.number = number;
random = new Random();
this.which = random.nextInt(2);
}
public void run() {
//start point?
}
public int getNumber() {
return number;
}
private void checkQuePosition() {
if (atFront())
tryToGetOn();
else
checkQuePosition();
}
//returns true if at front of que, else false
private boolean atFront() {
int position;
if (which == 0)
position = Playground.north.que.search(this);
else
position = Playground.south.que.search(this);
return position == 1;
}
private void tryToGetOn() {
Playground.roundabout.semaphore.acquire();
//get into the roundabout somehow
}
//releases semaphore, sleeps for a random period then calls joinQue(random 0 or 1)
public void getOff() {
Playground.roundabout.semaphore.release();
Thread.sleep(random.nextLong());
joinQue(random.nextInt(2));
}
private void joinQue(int w) {
this.which = w;
if (w == 0) {
//join north que
}
else
;//join south que
checkQuePosition();
}
}
I got here and now I am lost! Please assist