简体   繁体   English

循环执行3次Java

[英]loop executing 3 times java

Hi I cannot understand why in the world this loop executes 3 times in a second. 嗨,我不明白为什么这个循环每秒执行3次。 It is actually download speed calculation code and its is pretty straight forward. 它实际上是下载速度计算代码,非常简单。 it measures bytes done in previous 1 sec and then add it in a list then take average of all items in list then update gui and in last it sleep for 1 sec. 它测量前1秒钟完成的字节,然后将其添加到列表中,然后取列表中所有项目的平均值,然后更新gui,最后睡眠1秒钟。

private void update() {
    List<Float> list = new ArrayList<>();
    do {
        float averageSpeed = 0;
        // Calculating
        // I have a multiple threads which are downloading this file in segments
        // and all of them increment value of data.bytesDone when ever
        // they download a portion of data so I calculate bytesDone in one sec
        // and then take average of it using a list which contain speed values of
        // previous 20 sec. 
        float speed = (data.bytesDone.get() - currentBytes);
        currentBytes = data.bytesDone.get();

        System.out.println(speed);

        list.add(speed);
        if (list.size() > 20) {
            list.remove(0);
        }
        for (Float increment : list) {
            averageSpeed += increment;
        }
        averageSpeed /= list.size();

        // Updating Gui //

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } while (data.state.equals(State.ACTIVE) && data.bytesDone.get() != data.sizeOfFile);
}

EDIT: Guys I really cant understand why this loop is printing speed 3 times in a second it should always print only 1 time in a second. 编辑:伙计们,我真的不明白为什么此循环每秒打印3次,它总是应该每秒打印1次。 TY TY

Instead of using Thread.sleep(1000); 而不是使用Thread.sleep(1000); u can think about using this bit. 您可以考虑使用此位。

Right after your do{ 做完事后{

long startMili = System.currentTimeMillis();

and instead of your whole Thread.sleep(1000) thing put this in. 而不是整个Thread.sleep(1000)东西放进去。

long currentMili = System.currentTimeMilis();
while(currentMili - startMili < 1000){
    long currentMili = System.currentTimeMilis();
} 

This will ensure this code will loop 1 time per sec. 这将确保该代码每秒循环1次。

If this doesn't fix it, Then you might have some kind of threading issue since you are using a GUI. 如果这不能解决问题,那么由于使用的是GUI,因此可能存在某种线程问题。 How are you calling update? 您怎么称呼更新? Is there only one thread using update(). 是否只有一个线程使用update()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM