У меня возникла небольшая проблема с этим вопросом. Меня попросили завершить следующий класс.
public class UpDownTrack extends OpenTrack
{
//allowedDirection attribute required
private TrainDirection allowedDir;
//Add a constructor to set the initial state to down
public UpDownTrack()
{
allowedDir = DOWN;
}
//Override the useTrack method so that only one train at a time
//can use the track
public synchronized void useTrack(TrainDirection trainDir, int id)
{
try
{
enterTrack(trainDir, id);
traverse();
exitTrack(trainDir,id);
}
catch(Exception e)
{
System.out.println("Error" + e);
}
}
// Override the enterTrack method so,a train going in the opposite
// direction is only allowed to enter the track
//Then display that a train has entered the track
public synchronized void enterTrack(TrainDirection trainDir, int id)
{
if(allowedDir != trainDir)
{
try
{
System.out.println("Train " + id + " entered track, going " + trainDir);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
//Override the exitTrack method so that the direction is changed
//before the track is exited
//Then display that a train has exited the track
public synchronized void exitTrack(TrainDirection trainDir, int id)
{
System.out.println(" Train " + id + " left track, going " + trainDir);
trainDir = (trainDir == DOWN)? DOWN : UP;
notifyAll();
}
}
Методы переопределения из класса OpenTrack
public void useTrack(TrainDirection trainDir, int id)
{
enterTrack(trainDir, id);
traverse();
exitTrack(trainDir,id);
}
//This method doesn't currently check if it is safe to traverse the track.
//It just reports that a train has entered the track.
void enterTrack(TrainDirection trainDir, int id)
{
System.out.println("Train " + id + " entered track, going " + trainDir);
}
//This method currently just reports that a train has left the track
void exitTrack(TrainDirection trainDir, int id)
{
System.out.println(" Train " + id + " left track, going " + trainDir);
}
}
Проблема в том,я получаю неправильный вывод, я должен получить
Train 1 enters track going up
Train 1 leaves track
Train 3 enters track going down
Train 3 leaves track
Train 2 enters track going up
и так далее, но я получаю теперь последовательность и перемешал вывод