If I’m going to have a call to have a Java Thread go to sleep, is there a reason to prefer one of these forms over the other?
Thread.sleep(x)
or
TimeUnit.SECONDS.sleep(y)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
TimeUnit.SECONDS.sleep(x)will callThread.sleepafter validating that the timeout is positive. This means that as opposed toThread.sleep, anIllegalArgumentExceptionwill not be thrown when the timeout is negative.Other than that, the only difference is readability and using
TimeUnitis probably easier to understand for non-obvious durations (for example:Thread.sleep(180000)vs.TimeUnit.MINUTES.sleep(3)).For reference, see below the code of
sleep()inTimeUnit: