Java Reference
In-Depth Information
The
wait
and
notify
methods are an example of how threads are a built-in aspect of the
Java programming language. The methods have been a part of the language since the fi rst
version of Java, and their main usage is in implementing a producer/consumer model. If you
also understand that a thread needs to own the object's lock to invoke its
wait
or
notify
methods, you will have the information you need for answering the
wait
and
notify
questions on the SJCP exam.
Summary
This chapter covered the “Concurrency” objectives of the SCJP exam. The goal of this
chapter was to demonstrate how to create a thread in Java and also to understand the
various states of a thread once it is started.
You can write a thread in Java in two ways: write a class that implements the
Runnable
interface and wrap a new
Thread
object around an instance of your
Runnable
class, or
write a class that extends
Thread
and override the
run
method. From an object-oriented
point of view, writing a class that implements
Runnable
is the preferred technique.
We discussed the various states of a thread object and how a thread transitions from
one state to another. A thread in Java is
NEW
,
RUNNABLE
,
BLOCKED
,
WAITING
,
TIMED_WAITING
,
or
TERMINATED
. A
NEW
thread has been instantiated but not yet started. A
RUNNABLE
thread
is either currently executing on the CPU or waiting to be scheduled. A
BLOCKED
thread
has requested an unavailable lock and is waiting for that lock to be released by whichever
thread currently owns the lock. A
WAITING
thread has invoked the
wait
method on an
object and is waiting indefi nitely for a
notify
or
notifyAll
to be invoked on the object.
A thread enters the
TIMED_WAITING
state by invoking
wait
or
join
with a specifi ed timeout
or by invoking the
Thread.sleep
method. A
TERMINATED
thread has run to completion; it
cannot be started again.
Threads have a priority, and we discussed thread scheduling and the preemptive
behavior of threads. We also discussed the static
sleep
and
yield
methods of
Thread
and their effects on the currently running thread. The
sleep
method causes the currently
running thread to temporarily cease executing for a specifi ed amount of time. The
yield
method causes the currently running thread to temporarily pause and allow other threads
of the same priority to execute.
Threads need to be synchronized when accessing the same data in a process. Every
Object
in Java has an entity called its monitor lock that threads use to synchronize access
to the data of the object. Use the
synchronized
keyword to have a thread attempt to
acquire the monitor lock of an object. The
synchronized
keyword can obtain the lock of a
specifi c object's reference. You can also declare a method
synchronized
, in which case the
monitor lock of the object the method was invoked on is acquired.
Search WWH ::
Custom Search