设想:
一堆从北向南行驶的汽车(反之亦然)沿着一条两条车道行驶。过了一会儿,他们到了一座桥。这座桥只有一种方式,容量有限。一辆汽车需要 100 毫秒才能通过这座桥。不允许发生交通碰撞。
鉴于我需要计算,对于所有的汽车,
汽车请求进入桥梁和开始过桥之间的时间。
例如:如果一辆汽车向北行驶,到了桥上,发现桥上有向南行驶的汽车,它必须等待。需要等待多长时间?当然如果只有一辆车(桥是空的),车的等待时间=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!");
}
}