一堆汽車從北向南(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!");
}
}
我加了你的建議.. – 9628001
我們可以看看'bridge.getin(direction)'方法嗎? – Coffee
我會發布整個代碼,但我可能會因爲它包含至少45行而被皺眉,如果我被允許這樣做,我會做到這一點 – 9628001