覆盖方法和线程

时间:2011-05-10 21:23:36

标签: java multithreading override

我对这个问题有点疑问,我被要求完成以下课程。

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

等等,但我现在正在顺序和混乱输出

1 个答案:

答案 0 :(得分:0)

TrainDirection是你的一个类,当你将它的一个实例连接到一个字符串(例如这里:System.out.println(" Train " + id + " left track, going " + trainDir);)时,它会调用该类的toString方法。但是从toString()继承的默认Object返回对象哈希码而不是实际方向。因此,您需要覆盖类public String toString()中的TrainDirection方法,以便它向您返回有用的信息(例如火车的方向......)