Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to make code stall or sleep

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a metod that when called the first line of code I would like to write is to have the method stall for 10 miliseconds. How can I do this? This is not a thread.

I would just write a loop to stall, but it would finish at different times depending on what CPU is it is executed on.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even though it is not a separate thread, it still is running within the main thread. You can do:

to get the effect you want.
 
Tom Billings
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And to continue Joel's reply there's no way to guarantee a 10 ms sleep since it would mean that you're having exclusive control of the processor. Which Java, nor the OS would allow.
 
Tom Billings
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sleeping exactly 10 ms, that is.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Anthony Smith:
I have a metod that when called the first line of code I would like to write is to have the method stall for 10 miliseconds. How can I do this? This is not a thread.

I would just write a loop to stall, but it would finish at different times depending on what CPU is it is executed on.


Every program IS a thread. That is every program has at least ONE thread. So you can still use the methods from the Thread class as illustrated above.

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic