Java Reference
In-Depth Information
Communicate between threads
Suspend, resume, and stop threads
A lthough Java contains many innovative features, one of its most exciting is its built-in
support for multithreaded programming . A multithreaded program contains two or more
parts that can run concurrently. Each part of such a program is called a thread , and each
thread defines a separate path of execution. Thus, multithreading is a specialized form of
multitasking.
Multithreading Fundamentals
There are two distinct types of multitasking: process-based and thread-based. It is import-
ant to understand the difference between the two. A process is, in essence, a program that
is executing. Thus, process-based multitasking is the feature that allows your computer to
run two or more programs concurrently. For example, it is process-based multitasking that
allows you to run the Java compiler at the same time you are using a text editor or browsing
the Internet. In process-based multitasking, a program is the smallest unit of code that can
be dispatched by the scheduler.
In a thread-based multitasking environment, the thread is the smallest unit of dispatch-
able code. This means that a single program can perform two or more tasks at once. For
instance, a text editor can be formatting text at the same time that it is printing, as long as
these two actions are being performed by two separate threads. Although Java programs
make use of process-based multitasking environments, process-based multitasking is not
under the control of Java. Multithreaded multitasking is.
A principal advantage of multithreading is that it enables you to write very efficient pro-
grams because it lets you utilize the idle time that is present in most programs. As you
probably know, most I/O devices, whether they be network ports, disk drives, or the key-
board, are much slower than the CPU. Thus, a program will often spend a majority of its
execution time waiting to send or receive information to or from a device. By using multi-
threading, your program can execute another task during this idle time. For example, while
one part of your program is sending a file over the Internet, another part can be reading
keyboard input, and still another can be buffering the next block of data to send.
As you probably know, over the past few years, multiprocessor and multicore systems
have become commonplace. Of course, single-processor systems are still in widespread
use. It is important to understand that Java's multithreading features work in both types
of systems. In a single-core system, concurrently executing threads share the CPU, with
Search WWH ::




Custom Search