Hi i want to design an algorithim in Java that prevents deadlock for simple train simulator, im trying to solve the problem of two trains that want to move into the critical section Once a thread is in the critcal section it basically sleeps for a random period of time whilst the other waits Im not worried about starvation
So far i have this and its a rough implementation of dekkers algorithim.
public void runTrain() throws RailwaySystemError {
Clock clock = getRailwaySystem().getClock();
Railway nextRailway = getRailwaySystem().getNextRailway(this);
while (!clock.timeOut() && !errorOccurred()) {
announceIntention();
getFlag.putSFlag(this);
while(nextRailway.getFlag.hasFlag(this)) {
if(getSharedFlag.hasFlag(this)) {
getFlag.takeFlag(this);
while(getSharedFlag.hasFlag(this)) {
sleep();
}
getFlag().putFlag(this); // else
}
}
crossPass();
if (!getFlag.hasFlag(this)){
getSharedFlag.putFlag(this);
}
getFlag().takeFlag(this);
}
}
This code is almost the same for both trains.
Im trying to accomplish the same thing however exclusivley using Java semaphores the algorithim doesnt need to be bothered with starvation just preventing deadlock
Any help would be appreciated thanks