Java Reference
In-Depth Information
Chapter 8
Threads
8.1 Introduction
Threads in Java are processes that run in parallel within the Java Virtual Machine.
When the JVM runs on a single real processor the parallelism is, of course,
only apparent because of the high speed switching of threads in and out of the
processor. Yet even in that case, threading can provide significant advantages.
Forexample, while one thread deals with a relatively slow I/O operation such as
downloading a file over the network, other threads can do useful work. Threads
can assist in modularizing program design. An animation can assign different
threads to rendering the graphics, to sound effects, and to user interactions so
that all of these operations appear to take place simultaneously. Furthermore, a
JVM can assign Java threads to native OS threads (but isn't required to) and on
a multiprocessor system it could thus provide true parallel performance.
Java makes the creation and running of threads quite easy. We will concentrate
on the basics of threading and only briefly touch on the subtle complications that
arise when multiple threads interact with each other and need to access and modify
common resources. Such situations can result in data race , deadlock , and other
interference problems that result in distorted data or hung programs.
8.2 Introduction to threads
In Java you can create one or more threads within your program just as you can
run one or more programs in an operating system [1-4]. Most JVMs, in fact,
take great advantage of threads for such tasks as input/output operations and
user-interface event handling. Since the Java garbage collector always runs in a
separate thread, even the simplest Java program is actually multithreaded.
In the previous chapters we saw that Java applications begin when the JVM
invokes the main() method. (The application itself runs as a thread in the JVM.)
Instead of a main() , the thread processes begin and end with a method named
run() .You place code in run() to control the operations that you wish to
accomplish with the thread. The thread lives only as long as the process remains
within run() . When the thread process returns from the run() , the thread is
dead and cannot be resurrected.
253
Search WWH ::




Custom Search