File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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: 11955

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
I agree. Here's the link:
subject: Thread sleep times (Zzzzzzz)
jQuery in Action, 3rd edition