This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Thread sleep times (Zzzzzzz) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Thread sleep times (Zzzzzzz)" Watch "Thread sleep times (Zzzzzzz)" New topic

Thread sleep times (Zzzzzzz)

James MacDonald-Fawcett

Joined: Nov 17, 2003
Posts: 4
Hi, Can anyone help me figure this out please with thread sleep times. I want to make the thread sleep for a random time. but make the time betweem two boundaires. e.g. make the thread sleep between two and four seconds.
Currently I am doing this

but this only works for a single random number. Please help thanks!
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11653

don't remember the details on sleep, but...
if you're trying to get a random number betwee two values, say 15-27, you can do this...
your range of number is in this case 13. so, use the random method to get a vaule between 0-12. then, since your desired range is "shifted", add 15 to the result.
if i remember correctly (doubful this early in the morning), you pass the sleep method the number of milliseconds to sleep. you want betwee 2-4 seconds, so you want a range of 2000, and then shift it 2000.
however, i think sleep() also is how long to wait before signaling the thread is ready to work again. it's up to the JVM to finally decide when to wake it up... in other words, you might say "sleep for 2.8 seconds", but if the only other thread is in a section that takes 10 seconds, even after your thread "wakes up", there's no garuntee when it will. you only know it won't wake up BEFORE your 2.8 seconds...
i think that's how it works.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Thread sleep times (Zzzzzzz)