Java Reference
In-Depth Information
each thread receiving a slice of CPU time. Therefore, in a single-core system, two or more
threads do not actually run at the same time, but idle CPU time is utilized. However, in
multiprocessor/multicore systems, it is possible for two or more threads to actually execute
simultaneously. In many cases, this can further improve program efficiency and increase
the speed of certain operations.
A thread can be in one of several states. It can be
running
. It can be
ready to run
as soon
as it gets CPU time. A running thread can be
suspended
, which is a temporary halt to its
execution. It can later be
resumed
. A thread can be
blocked
when waiting for a resource. A
thread can be
terminated
, in which case its execution ends and cannot be resumed.
Along with thread-based multitasking comes the need for a special type of feature called
synchronization
, which allows the execution of threads to be coordinated in certain well-
defined ways. Java has a complete subsystem devoted to synchronization, and its key fea-
tures are also described here.
If you have programmed for operating systems such as Windows, then you are already
familiar with multithreaded programming. However, the fact that Java manages threads
through language elements makes multithreading especially convenient. Many of the de-
tails are handled for you.
The Thread Class and Runnable Interface
Java's multithreading system is built upon the
Thread
class and its companion interface,
Runnable
. Both are packaged in
java.lang
.
Thread
encapsulates a thread of execution. To
create a new thread, your program will either extend
Thread
or implement the
Runnable
interface.
The
Thread
class defines several methods that help manage threads. Here are some of
the more commonly used ones (we will be looking at these more closely as they are used):
Method
Meaning
final String getName( )
Obtains a thread's name.
final int getPriority( )
Obtains a thread's priority.
final boolean isAlive( )
Determines whether a thread is still running.
final void join( )
Waits for a thread to terminate.
void run( )
Entry point for the thread.
static
void
sleep(long
milli-
Suspends a thread for a specified period of milli-
seconds.
seconds
)
void start( )
Starts a thread by calling its run( ) method.