Java Reference
In-Depth Information
Blocking
Blocking occurs any time a thread has to stop and wait for a resource it doesn't have.
The most common way a thread in a network program will voluntarily give up control
of the CPU is by blocking on I/O. Because CPUs are much faster than networks and
disks, a network program will often block while waiting for data to arrive from the
network or be sent out to the network. Even though it may block for only a few milliā€
seconds, this is enough time for other threads to do significant work.
Threads can also block when they enter a synchronized method or block. If the thread
does not already possess the lock for the object being synchronized on and some other
thread does possess that lock, the thread will pause until the lock is released. If the lock
is never released, the thread is permanently stopped.
Neither blocking on I/O nor blocking on a lock will release any locks the thread already
possesses. For I/O blocks, this is not such a big deal, because eventually the I/O will
either unblock and the thread will continue or an IOException will be thrown and the
thread will then exit the synchronized block or method and release its locks. However,
a thread blocking on a lock that it doesn't possess will never give up its own locks. If one
thread is waiting for a lock that a second thread owns and the second thread is waiting
for a lock that the first thread owns, deadlock results.
Yielding
The second way for a thread to give up control is to explicitly yield. A thread does this
by invoking the static Thread.yield() method. This signals to the virtual machine that
it can run another thread if one is ready to run. Some virtual machines, particularly on
real-time operating systems, may ignore this hint.
Before yielding, a thread should make sure that it or its associated Runnable object is
in a consistent state that can be used by other objects. Yielding does not release any locks
the thread holds. Therefore, ideally, a thread should not be synchronized on anything
when it yields. If the only other threads waiting to run when a thread yields are blocked
because they need the synchronized resources that the yielding thread possesses, then
the other threads won't be able to run. Instead, control will return to the only thread
that can run, the one that just yielded, which pretty much defeats the purpose of yielding.
Making a thread yield is quite simple in practice. If the thread's run() method simply
consists of an infinite loop, just put a call to Thread.yield() at the end of the loop. For
example:
public void run () {
while ( true ) {
// Do the thread's work...
Thread . yield ();
}
}
Search WWH ::




Custom Search