Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread.sleep() not working as expected

 
Eric Daly
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am studying for SCJP using Kathy Sierra and Bert Bates SCJP 5 study guide. However, I figured this would be the best place to ask this question; it seems simple enough. In the threads chapter, it mentions that Thread's sleep() method takes a time in milliseconds as an argument. There are 1000 milliseconds in one second, so if I pass 1000 to the Thread.sleep() method, it should sleep for *at least* one second. I know there are no guarantees, but for some reason on my system, it is consistently "asleep" for 10 seconds. I have this code:

There is a nice, precise 10 second pause between each print statement. When I use sleep(100) there is a nice 1 second pause each time. Am I missing something???
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The sleep is indeed only sleeping for 1 second each iteration, however you're only executing a print statement every 10 iterations, therefore you are correctly observing 10 seconds between prints.
 
Eric Daly
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oooooohhhhh. Haha, I better get on top of these things if I plan on passing the SCJP test. It's like all this studying is making me dumber. Thanks for the help.
 
Norm Radder
Ranch Hand
Posts: 728
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you'd add a few println() statements to the code you'd see what it was doing.
 
Eric Daly
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yea I know... I should have spent a couple minutes trying to actually figure it out... I was too busy trying to understand how Threads work though, and this was just a thought in the back of my mind that I wanted to ask about.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic