2011-05-10 37 views
0

Iam對這個問題有點問題我被要求完成以下課程。覆蓋的方法和線程

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 

等,但即時通訊現在越來越序列和混亂up輸出

回答

0

TrainDirection是你的一類,當你連接一個我將它保存爲一個字符串(例如:System.out.println(" Train " + id + " left track, going " + trainDir);),它調用該類的toString方法。但是從Object繼承的默認toString()返回對象散列碼而不是實際的方向。所以你需要覆蓋TrainDirection中的public String toString()方法,這樣它會向你返回一個有用的信息(比如火車的方向......)