Java Reference
In-Depth Information
CHAPTER 4
Threads
A thr ead is a unit of program execution that runs independently from other
threads. Java programs may consist of multiple threads of execution that behave as
if they were running on independent CPUs, even when the host computer actually
has only a single CPU. In many programming languages, multithreading capabili-
ties are added on as an afterthought. In Java, however, they are integrated tightly
with the language and its core packages:
The java.lang.Runnable interface defines a run() method that serves as the
block of code a thread executes. When that method exits, the thread stops
running.
The java.lang.Thread class represents a thread; it defines methods for setting
and querying thread properties (such as execution priority level) and for start-
ing the execution of a thread.
The synchronized statement and modifier can be used to write blocks of
code and entire methods, respectively, that require a thread to obtain a lock
before executing the block or method. This mechanism ensures that two
threads can't run the block or method at the same time, to avoid problems
with different threads putting shared data in an inconsistent state.
The wait() and notify() methods of java.lang.Object can be used to sus-
pend threads and wake them up again.
The use of threads is common in Java programming; it is not possible to confine a
discussion of them to just one chapter. We'll start with some simple examples here.
We'll see threads again in Chapter 5, Networking , where they are quite useful for
writing network server programs that can respond to multiple client requests
simultaneously. Threads also appear in Chapter 11, Graphics , and Chapter 15,
Applets , where they are used to produce animation effects.
Search WWH ::




Custom Search