Java Reference
In-Depth Information
The two threads have the same priority and politely yield to each other. As you can see
by the output, each thread is getting equal time on the CPU. In a real-world scenario, you
might not call
yield
quite this often, but in general it is a good method to call whenever
you want your threads to get along with other threads and not hog the CPU unnecessarily.
Blocked Threads
Threads access shared memory in a process and therefore need to be synchronized. The
upcoming section “Thread Synchronization” discusses the
synchronized
keyword and the
details you need to know about thread synchronization. Synchronization in Java is done at
the object level, where threads ask for an object's lock before entering synchronized code.
If a thread asks for a lock and the lock is already in use by another thread, it becomes a
blocked thread
.
A
blocked thread stays blocked until the requested lock becomes available,
at which point it returns to the runnable state, as Figure 5.4 shows.
FIGURE 5.4
A thread goes from
RUNNABLE
to
BLOCKED
when a synchronized lock is
unavailable.
RUNNABLE
CPU
scheduled
lock
becomes
available
synchronized
BLOCKED
The
getState
method of a blocked thread returns the
BLOCKED
value of the
Thread
.State
enumeration.
Waiting and Timed-Waiting Threads
The Java language has built-in threading capabilities, as demonstrated by the
wait
and
notify
methods of the
Object
class. The
wait
method invoked on an
Object
causes the
thread to wait until another thread calls
notify
on the same
Object
. We discuss the details
in the section “The
wait
,
notify
, and
notifyAll
Methods,” but for now let's see the effect
these methods have on the state of a thread.
The
wait
method in
Object
has three overloaded versions:
public final void wait() throws InterruptedException
public final void wait(long timeout) throws InterruptedException
public final void wait(long timeout, int nanos) throws InterruptedException
The
wait
method causes the thread to wait for either
notify
or
notifyAll
to be invoked
on the same object or wait for the specifi ed time to elapse. The
wait
and
notify
methods
cannot be invoked unless the thread has the object's lock. When
wait
is invoked, the lock
Search WWH ::
Custom Search