简体   繁体   中英

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.

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 .

Thread.sleep 直接通过 JNI 调用系统函数,就像 Windows 中的 Sleep() 函数

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