簡體   English   中英

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

[英]time calculation between method and Thread.sleep()

場景:

一堆從北向南(viceversa)行駛的汽車沿着兩條車道行駛。 過了一會兒,他們到達了一座橋。 橋只是一種方式,容量有限。 一輛汽車要花費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!");
        }
    }

如果第二輛車在第一輛車已經在橋上花費了75毫秒時到達橋上,那么對我來說第二輛車只等待25毫秒就顯得合乎邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM