Java Reference
In-Depth Information
thread that is displaying a GUI on the screen, a second thread in the back-
ground that is downloading a file from the Internet, and a third thread that is
waiting for the user to interact with the GUI.
I need to define another term related to threads: process . A process consists of
the memory space allocated by the operating system that can contain one or
more threads. A thread cannot exist on its own; it must be a part of a process.
A process remains running until all of the non-daemon threads are done
executing.
You are familiar with processes, because each time you run a program on
your computer, you start a process. Today's operating systems are multipro-
cessing (often called multitasking). You can run multiple processes at the same
time. For example, you can play Solitaire while checking your email with Out-
look and surfing the Internet with Netscape Navigator. Just to clarify, we will
not discuss multiple processes in this chapter. What we will discuss is multiple
threads in a single process.
A daemon thread , by definition, is a thread that does not keep the process exe-
cuting. Use a daemon thread for a task that you want to run in the background
only while the program is still running. The garbage collector of the JVM
process is a good example of a daemon thread. The JVM wants the garbage
collector to always be running in the background, freeing memory of unused
objects. However, if the garbage collector is the only thread running, there is
no need for the JVM process to continue executing.
Classroom Q & A
Q: How many threads can a process have?
A: As many threads as it can handle in its memory space. I have seen
applications with thousands of threads. Of course, these applica-
tions were running on large servers with lots of memory and mul-
tiple CPUs.
Q: And all of these threads are running at the same time?
A: Well, yes and no. To be more precise, a process can have multiple
threads that are runnable at the same time. However, the number
of threads actually running at any given time is dependent on the
number of CPUs (processors) available.
Q: So how many threads can run on a CPU at one time?
A: Just one! That means your typical desktop computer with its one
CPU can execute only one thread at a time.
Search WWH ::




Custom Search