Hello,
I have been fighting with this assignment for almost 3 week now and it's almost ready besides one part that I simply don't understand. I would appreciate if someone could maybe translate it into "simple English" for me and maybe give me a little guidance. Basically we are writting a small train track simulation program ( I will include the two classes I have created later) and we are now asked to create method that will alternate in direction by presupposing that trains follow a timetable which prevents trains travelling in the same direction from colliding with each other.
Here's the question:
"The enterTrack() method should not allow a thread to proceed if:
•
the direction of travel is UP, and either
there is a DOWN thread currently using the track, or
the number of UP threads currently on the track is already greater than
two;
or
•
its mode is DOWN and any other threads are currently using the track.
exitTrack(TrainDirection dir) which records the fact that a
thread has finished using the track and wakes up any threads that are
waiting."
And my question is how do I go about referencing to the threads within these methods?
Here's the code:
The Train class:
public class Train extends Thread
{
private Track track;
private int trainId;
private TrainDirection direction;
public Train(TrainDirection dir, int id, Track tr)
{
direction = dir;
trainId = id;
track = tr;
}
public void run()
{
track.useTrack(direction, trainId);
}
}
And here's the Track class I am supposed to change:
public class Track
{
public Track()
{
}
public void useTrack(TrainDirection dir, int id)
{
System.out.println("Train " + id + " entering track, going " + dir);
traverse();
System.out.println("Train " + id + " leaving track, going " + dir);
}
public void enterTrack(TrainDirection dir)
{
}
public synchronized void exitTrack(TrainDirection dir)
{
}
/* You do not need to change this method */
private void traverse()
{
try
{
TimeUnit.MILLISECONDS.sleep(500);
}
catch (InterruptedException ie)
{
System.out.println(ie);
}
}
Sorry for the long post :) I am not expecting a solution, as mentioned I just need to know how I am supposed to use threads directly in this method.
Many thanks for your help and sorry if I am not clear enough in my post but Java still scares me:)