Skip to main content
Sleep, Yield, and Join
- Sleeping is used to delay execution for a period of time, and no locks are released when a thread goes to sleep.
- A sleeping thread is guaranteed to sleep for at least the time
specified in the argument to the sleep() method (unless it's
interrupted), but there is no guarantee as to when the newly awakened
thread will actually return to running.
- The sleep() method is a static method that sleeps the currently
executing thread's state. One thread cannot tell another thread to
sleep.
- The setPriority() method is used on Thread objects to give threads a
priority of between 1 (low) and 10 (high), although priorities are not
guaranteed, and not all JVMs recognize 10 distinct priority levels—some
levels may be treated as effectively equal.
- If not explicitly set, a thread's priority will have the same priority as the priority of the thread that created it.
- The yield() method may cause a running thread to back out if there
are runnable threads of the same priority. There is no guarantee that
this will happen, and there is no guarantee that when the thread backs
out there will be a different thread selected to run. A thread might
yield and then immediately reenter the running state.
- The closest thing to a guarantee is that at any given time, when a
thread is running it will usually not have a lower priority than any
thread in the runnable state. If a low-priority thread is running when a
high-priority thread enters runnable, the JVM will usually preempt the
running low-priority thread and put the high-priority thread in.
- When one thread calls the join() method of another thread, the
currently running thread will wait until the thread it joins with has
completed. Think of the join() method as saying, "Hey thread, I want to
join on to the end of you. Let me know when you're done, so I can enter
the runnable state."