简体   繁体   中英

loop executing 3 times java

Hi I cannot understand why in the world this loop executes 3 times in a second. 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.

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. TY

Instead of using 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.

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

This will ensure this code will loop 1 time per sec.

If this doesn't fix it, Then you might have some kind of threading issue since you are using a GUI. How are you calling update? Is there only one thread using update().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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