Scruffy
Scruffy

Reputation: 580

Wait for a time frame in Java: how does Thread.sleep(int) work?

Conventionally, I delay my programs for a short time with Thread.sleep(int) surrounded with an e.printStackTrace() try/catch block. I want to do away with the exception handling. I wrote this function:

private static void pause(int millis) {
    long end = System.currentTimeMillis() + millis;
    while(System.currentTimeMillis() <= end) {
        // Do nothing
    }
}

But using it uses 15% CPU (an audible affair). How does Thread.sleep(int) pause without unacceptable CPU usage? My uneducated guess is that it performs some activity which is time consuming, not requiring of much CPU effort, and rather pointless other than for passing time.

Upvotes: 1

Views: 386

Answers (2)

shmosel
shmosel

Reputation: 50726

Thread.sleep() doesn't do any activity; the thread gets suspended. But if you're just trying to circumvent exception handling, why not add that to your helper method?

private static void pause(int millis) {
    try {
        Thread.sleep(millis);
    } catch (InterruptedException e) {
        // Do nothing
    }
}

If you want to make sure your method never completes too soon, you can put the try-catch inside your while loop.

By the way, technically speaking, a loop doesn't require a body, so you could replace the curly braces with a semicolon in your method.

UPDATE: Actually... don't swallow interrupts.

Upvotes: 3

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

Thread.sleep calls a system function directly via JNI, like The Sleep() function in Windows

Upvotes: 0

Related Questions