Java 方法和线程之间的时间计算。sleep()
情景: 一大群汽车从北向南(viceversa)沿着一条双车道道路行驶。 过了一会儿,他们到达一座桥。这座桥是单向的,承载能力有限。 一辆汽车花100毫秒通过这座桥。不允许发生交通碰撞 考虑到我需要计算,对于所有的车 请求进入驾驶台的车辆与驾驶台之间的时间 开始穿越 例如:如果一辆向北行驶的汽车到达桥上,发现桥上有车向南行驶,它就会停下来 我必须等一下。要等多久? 当然,如果只有一辆车(桥是空的),车的等待时间是=0。 如果有两辆车(方向相反,桥梁通行能力=1),则时间应为:0和100ms 根据我写的代码,一辆车的等待时间为零,而另一辆车的等待时间小于100,这是错误的 有什么原因吗 在我看来,这只是一个时间问题:Java 方法和线程之间的时间计算。sleep(),java,Java,情景: 一大群汽车从北向南(viceversa)沿着一条双车道道路行驶。 过了一会儿,他们到达一座桥。这座桥是单向的,承载能力有限。 一辆汽车花100毫秒通过这座桥。不允许发生交通碰撞 考虑到我需要计算,对于所有的车 请求进入驾驶台的车辆与驾驶台之间的时间 开始穿越 例如:如果一辆向北行驶的汽车到达桥上,发现桥上有车向南行驶,它就会停下来 我必须等一下。要等多久? 当然,如果只有一辆车(桥是空的),车的等待时间是=0。 如果有两辆车(方向相反,桥梁通行能力=1),则时间应为:0和100ms 根据
bridge.getin(direction);
及
提前谢谢
下面是我指的代码的一部分:
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毫秒是合乎逻辑的。如果第二辆车在第一辆车已经在桥上花了75毫秒的时候来到桥上,在我看来,第二辆车只需等待25毫秒是合乎逻辑的。我们能看到
桥。getin(方向)
方法吗?我会发布整个代码,但我可能会皱眉,因为它至少包含45行。如果允许我这样做,我会这样做。我们能看到桥。getin(方向)吗
method?我会发布整个代码,但我可能会不高兴,因为它至少包含45行。如果允许我这样做,我会这样做。这是正确的。同样,如果只有一辆车,等待时间为零。这是正确的。同样,如果只有一辆车,等待时间为零
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!");
}
}