Since you can't be sure whether you'll be working with a cooperative or preemptive model, it's important not to assume preemption is available. CPU-intensive threads should yield control at periodic intervals. There are four different ways a thread can give up control and allow other threads to run.
Thread.yield()
.Blocking occurs when a thread has to wait for an operation to complete. Most commonly this is an I/O operation, particularly one involving a network connection. It's also possible for a call to block while waiting for user input. Placing I/O and user input in separate, high priority threads is often a good idea because it allows the computer to be used more efficiently. Other CPU intensive threads can get a lot of work done while waiting for data to come in over the network or the user to type a character or two.
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()