Thread.yield()
.
When a program calls Thread.yield()
, it's signifying that the current thread, the one which called Thread.yield()
, is willing to step aside in favor of another thread. The VM looks to see if any other threads of the same priority are ready to run. If any are, it pauses the currently executing thread and passes control to the next thread in line. If no other threads of the same or higher priority are ready to run, control returns to the thread that yielded. Thus Thread.yield()
only signals a willingness to give up control. It does not guarantee that the thread will actually stop. That depends completely on what other threads exist and what their status is.
If a thread definitely wants to give up control for a period of time, whether or not there are any other threads of equal or higher priority ready to run, then it can call sleep()
. The sleep()
methods put a thread to sleep for a certain amount of time during which even lower priority threads may have an opportunity to run.
public static void sleep(long milliseconds) throws InterruptedException
public static void sleep(long milliseconds, int nanoseconds) throws InterruptedException
Finally, a thread can be suspended. When a thread calls suspend()
(or more commonly when a different thread invokes the thread's suspend()
method), it is paused indefinitely until some other thread starts it running again by invoking its resume()
method.
public final void suspend()
public final void resume()