从随机持续时间获得平均值

时间:2018-05-13 11:09:55

标签: java multithreading concurrency

我正在尝试打印此代码末尾的持续时间的最大值,最小值和平均值,但我不太确定如何在特定数组中存储随机持续时间以在结束后显示它。以下是代码:

public void test(){
 int max;
 int average;
 int min;

    long duration=2;
    try
    {   System.out.println("Bus Needs Cleaning" + "\n");
        Thread.sleep(1000);
        System.out.println("Bus getting cleaned");
        Thread.sleep(1000);
        duration = (long)(Math.random()*20);
        TimeUnit.SECONDS.sleep(duration);

    }
    catch(InterruptedException iex)
    {
    }

 System.out.println("Cleaner completed cleaning in" + duration + "Seconds");
 System.out.println("Bus Leaves");

 System.out.println("Average Waiting Time: " + average + " | Maximum: "+ max + " | Minimum" + min +"\n");

}

非常感谢任何帮助,谢谢!

编辑:有5辆公共汽车进出并显示不同的持续时间,他们都经历了清洁阶段

1 个答案:

答案 0 :(得分:0)

请尝试这个。据我所知

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class BusRandom {

public static void main(String[] args) {
    new BusRandom().test();
}

public void test() {
    long max = 0;
    double average = 0;
    long min = Long.MAX_VALUE;
    int totalBuses=5;//change accordinly
    List<Long> randomList = new ArrayList<>();
    long duration = 2;
    try {
        for (int i = 0; i <totalBuses; i++) {
            System.out.println("Bus Needs Cleaning" + "\n");
            Thread.sleep(1000);
            System.out.println("Bus getting cleaned");
            Thread.sleep(1000);
            duration = (long) (Math.random() * 20);
            randomList.add(duration);
            TimeUnit.SECONDS.sleep(duration);
            System.out.println("Cleaner completed cleaning in" + duration + "Seconds");
            System.out.println("Bus Leaves");
            max=max>duration?max:duration;
            min=min<duration?min:duration;
        }
    } catch (InterruptedException iex) {
    }
    double sum=0;
    for(long l:randomList){
        sum+=l;
    }
    average=(double) (sum/randomList.size());
    System.out.println("Average Waiting Time: " + average + " | Maximum: " + max + " | Minimum" + min + "\n");

}
}