2021-09-28 19:10:27 +10:00

121 lines
3.4 KiB
Java

import java.util.concurrent.*;
public class P1_War implements Runnable{
Semaphore sem;
private int id; //ID number of the WAR
private boolean atDock; //Is the WAR at the dock? True if at dock
private int trackNum; //Which track does the WAR operate in? 1 or 2?
boolean finished = false;
int[] tracks;
/**
* WAR (Wharehouse Assistance Robot) object
* @param idInput ID number for the WAR
* @param trackNumInput The track that the WAR is on
* @param atDockInput Is the WAR at the dock (True) or at Storage (False)
*/
public P1_War(int idInput, int trackNumInput, boolean atDockInput, Semaphore intersection,int[] tracksInput) {
id = idInput;
atDock = atDockInput;
trackNum = trackNumInput;
this.sem=intersection;
tracks = tracksInput;
}
public void run()
{
String loadedState;
String destination;
while(!finished)
{
// if(tracks[0]>=150 && tracks[1] >=150)
// {
// finished=true;
// break;
// }
//if(!finished)
{
if(atDock)
{
loadedState = " (Loaded) ";
destination = "Dock";
}
else
{
loadedState = " (Unloaded) ";
destination = "Storage";
}
if(!(tracks[0]>=150 && tracks[1] >=150))
{
System.out.println("WAR-"+id+loadedState+"Waiting at the Intersection. Going towards "+destination+trackNum);
}
//aquire semaphore
sem.acquireUninterruptibly();
if(tracks[0]>=150 && tracks[1] >=150)
{
finished=true;
}
if(!finished)
{
for(int i = 1; i<=3; i++)
{
System.out.println("WAR-"+id+loadedState+"Crossing intersection Checkpoint "+i+".");
try {
Thread.sleep(2);
} catch (InterruptedException e) {
// Don't care
//e.printStackTrace();
}
}
System.out.println("WAR-"+id+loadedState+"Crossed the intersection.");
atDock=!atDock;
if(trackNum == 1)
{
tracks[0]++;
}
else if (trackNum == 2)
{
tracks[1]++;
}
System.out.println("Total crossed in Track1 "+tracks[0]+" Track2 "+tracks[1]);
}
sem.release();
}
}
}
//Getters
public int getID()
{
return id;
}
public boolean getAtDock()
{
return atDock;
}
public int getTrackNum()
{
return trackNum;
}
//Setters
public void setAtDock(boolean atDockInput)
{
atDock=atDockInput;
}
public void setFinished(boolean input)
{
finished = input;
}
}