简体   繁体   中英

How to use thread.sleep() properly in Java?

I see a lot of code snippets below in our code base:

        try {
            Thread.sleep((int)Millis);
        } catch (InterruptedException e) {
        }

Apparently, an empty catch clause is not a good idea. If the thread is interrupted, the sleep period will not be finished completely.

I am wondering if there's no logic in my code to interrupt the thread, could JVM interrupt a thread which is sleeping? If so, how to ensure a thread sleep to the end of its specified period?

And what's the best practice to use thread.sleep() method?

Since comments already link to the answers on the question why you should catch InterruptedException, I will focus on your second question - about the use of Thread.sleep() .

This method is handy when you want to introduce a short pause into your thread execution. For example, imagine you have to update 100 000 rows in a database, but in order to lower the impact on the database you are required to introduce breaks of, say 2 seconds, between your update queries. One of the quick-and-dirty solutions will look like this:

for (int i = 0; i < 100 000) {
   statement.executeUpdate(....);
   Thread.sleep(2000);
}

Here you after each update you wait 2 seconds and only after that go to executing the next update. (remember is just an illustration of the concept, not full blown production-ready code to be copy-pasted).

Another typical situation happens when you wait for some resource to be available and do not want to waste CPU cycles while awaiting for it to become available. For example, you make an asynchronous call that returns a Future and you want to wait for the the asynchronous computation to complete to go on with your logic. Its generally done like that:

    int someNumberOfMillisToSleep = //some number;
    ...

    while (!future.isDone()) {
        Thread.sleep(someNumberOfMillisToSleep );
    }

    /*now that future.isDone() returned true, 
you can get the result and go on with on with you logic
   */ 
    int res = future.get();

    //some computation here

So having nothing more important to do you sleep waiting for the asynchronous computation to be completed in order not generate useless load on the CPU.

It is also important that in contrast to wait the method sleep retains locks on the monitors that were acquired by the thread. That means you can use it in a synchronized block and expect the thread to be able to continue the work it was doing in this block after the sleep returns (of course, if the thread was not interrupted).

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