문제

I am writing single threaded program that requires a pause after each operation. (pause = random value between 1 and 60 seconds).

So a wrote method like this:

public void freeze() throws InterruptedException {
    Thread.sleep(nextFreezeDurationSec * 1000);
    calculateNextFreezeDuration();
}

I discovered a problem while looking through program log. Аpparently, for some unknow for me reason, after 500-700 operations it puts my program to sleep for a much bigger amount of time (once it was greater than an hour)

And I wrote another method:

public void freeze() {
    long nextFreezeEnd = System.currentTimeMillis() + (nextFreezeDurationSec * 1000);
    while (System.currentTimeMillis() < nextFreezeEnd) {
      /*NOR*/
    }
    calculateNextFreezeDuration();
}

This one works fine. But it eats CPU like crazy.

I would be grateful for any advice on this issue.

도움이 되었습니까?

다른 팁

The second one is eating CPU because it is constantly calculating the nextFreezeDuration in the while loop.

Every time that it hits the while (which is infinitely until the while loop completes), it does a calculation. Research how to take a make it wait for a couple of milliseconds at least before letting it re-hit the while loop

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top