States of a thread
1. Yielding: Yield is a static method. Operates on current
thread. Moves the thread from running to ready state. If there
are no threads in ready state, the yielded thread may continue
execution, otherwise it may have to compete with the other threads
to run. Run the threads that are doing time-consuming operations
with a low priority and call yield periodically from those threads
to avoid those threads locking up the CPU.
2. Sleeping: Sleep is also a static method. Sleeps for a
certain amount of time. (Passing time without doing anything
and w/o using CPU) After the time expires, the sleeping thread
goes to ready state. It may not execute immediately after the
time expires. If there are other threads in ready state, it
may have to compete with those threads to run. The correct statement
is the sleeping thread would execute some time after the specified
time period has elapsed f interrupt method is invoked on a sleeping
thread, the thread moves to ready state. The next time it begins
running, it executes the Interrupted Exception handler.
3. Waiting: wait, notify and notifyAll methods are not called
on Thread, they're called on Object. Because the object is the
one which controls the threads in this case. It asks the threads
to wait and then notifies when its state changes. It's called
a monitor. Wait puts an executing thread into waiting state.
(to the monitor's waiting pool). Notify moves one thread in
the monitor's waiting pool to ready state. We cannot control
which thread is being notified. NotifyAll is recommended. NotifyAll
moves all threads in the monitor's waiting pool to ready. These
methods can only be called from synchronized code, or an IllegalMonitorStateException
will be thrown. In other words, only the threads that obtained
the object's lock can call these methods.
4. Suspending: A thread that receives a suspend call, goes
to suspended state and stays there until it receives a resume
call on it. A thread can suspend it itself, or another thread
can suspend it. But, a thread can be resumed only by another
thread. Calling resume on a thread that is not suspended has
no effect. Compiler won't warn you if suspend and resume are
successive statements, although the thread may not be able to
be restarted.
5. Blocking: Methods that are performing I/O have to wait
for some occurrence in the outside world to happen before they
can proceed. This behavior is blocking. If a method needs to
wait an indeterminable amount of time until some I/O takes place,
then the thread should graciously step out of the CPU. All Java
I/O methods behave this way. A thread can also become blocked,
if it failed to acquire the lock of a monitor.
Java leaves the implementation of thread scheduling to JVM
developers. Two types of scheduling can be done.
1.Pre-emptive Scheduling.
2.Time-sliced or Round Robin Scheduling