2012-06-03 67 views
1

場景:方法和Thread.sleep之間的時間計算()

一堆汽車從北向南(viceversa)沿着雙車道公路行駛。 過了一會兒,他們到達了一座橋。這座橋只有一條路,容量有限。 一輛車花費100ms通過橋。不允許交通碰撞。

考慮到我需要計算,對於所有的汽車,

進入橋樑和 開始交叉的車請求之間的時間。

例如:如果一個車,北上,得到的橋樑和發現,有在橋上車南下,它 必須等待。它需要等多久? 當然,如果只有一輛車(橋是空的),汽車的等待時間爲0. 如果有兩輛汽車(相反的方向,橋的容量= 1),時間應該是:0和100ms。

根據我寫的代碼,我得到零等待時間的一輛車,但less than 100其他車是錯誤的。

有什麼理由呢?

在我看來,這只是獲得之間的時間的問題:提前

bridge.getin(direction); 

Thread.sleep(100); 

感謝。

這裏我指的是部分代碼:

public void run(){ 
     Random rand = new Random(); //class for random numbers 

     int timeToSleep = 10 + rand.nextInt(11); 
     try { 
      Thread.sleep(timeToSleep); //simulate the arrival at the bridge (it's not part of the calculation) 

      executionTime = System.currentTimeMillis(); //starts recording time 

      // The bridge is a one way bridge (it should avoid traffic collision) 

      bridge.getin(direction);  //method call (thread asks to enter the shared section) 

      executionTime = System.currentTimeMillis() - executionTime; // get time spent by a thread before crossing 

      Thread.sleep(100);    //simula l'attraversamento del ponte 

      bridge.getout(direction);   //leaves the bridge 

     } catch (InterruptedException e) { 
      System.out.println("Car "+id+": interrupted!"); 
     } 
    } 
+0

我加了你的建議.. – 9628001

+0

我們可以看看'bridge.getin(direction)'方法嗎? – Coffee

+0

我會發布整個代碼,但我可能會因爲它包含至少45行而被皺眉,如果我被允許這樣做,我會做到這一點 – 9628001

回答

1

如果第二輛車來當第一輛車上的橋樑已花了75個米利斯橋,似乎合乎邏輯的我,第二輛車僅等25毫米。

+0

這是正確的..所以,如果只有一輛車在等待時間是零 – 9628001