场景:
一群从北到南(反之亦然)的汽车沿着两条车道行驶。 过了一会儿,他们到达一座桥。这座桥只有单向,通行能力有限。 一辆车通过这座桥需要100ms。不允许发生交通碰撞。
鉴于我需要计算所有汽车,
the time between a car request for entering the bridge and the beginning of crossing.
举个例子:如果一辆汽车向北行驶,到了桥上,发现桥上有向南行驶的汽车, 必须等待。需要等多久? 当然,如果只有一辆车(桥是空的),那么汽车的等待时间= 0。 如果有两辆车(方向相反,桥梁容量=1),时间应为:0 和 100ms。
根据我编写的代码,一辆车的等待时间为零,但另一辆车的等待时间小于 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!");
}
}
最佳答案
如果第二辆车到达桥时第一辆车已经在桥上花费了 75 毫秒,那么在我看来,第二辆车只等待 25 毫秒是合乎逻辑的。
关于java - 方法和 Thread.sleep() 之间的时间计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10871297/