Sunday 2 March 2014

Thread.sleep() and Thread.yield()

An interesting comparison to make with no real loud, resounding solution at all.

Thread.sleep(long millis) typically causes the currently running thread to go to a sleep state. What this essentially means is that it actively uses CPU cycles to sleep for the duration specified in millis. After this sleep, however, there is no guarantee that the thread will continue to execute and may be moved to runnable state where it will join the queue of runnable threads waiting for execution.

Thread.yield() causes a current thread to defer its execution state to another thread of equal or higher priority. Apparently, the JLS does not provide guarantees that this thread will indeed be moved to the runnable state from running state.

It must be noted that neither of these methods result  in a thread forfeiting its locks, so they should be used with caution.

No comments:

Post a Comment