mike
mike

Reputation: 1338

Is there any benefit to Thread.sleep() in an infinite loop?

I have a construct wherein a variable is constantly updated based on how long the application has been open.

while (playTime < allowedTime) {
    endTimeSec = (int) (System.currentTimeMillis() / MILLISECONDS);
    playTime = endTimeSec - startTime;
}

This check is constantly running on a Thread separate from where my actual app is. My question is, since I'm basically concerned with accuracy down to the second, would there be any benefit to having Thread.sleep(1000) every time the loop is iterated?

Upvotes: 2

Views: 1245

Answers (1)

rgettman
rgettman

Reputation: 178303

Yes, there is a benefit to Thread.sleep(1000); in this case. That will put your Thread to sleep for a second, so it doesn't consume CPU resources during this time.

It's as if you are taking your kids on vacation on a long car ride. Instead of the kids asking "Are we there yet?" once every microsecond, they will ask once every second. That's much better.

Upvotes: 10

Related Questions