Java Reference
In-Depth Information
threads to make this happen. There may or may not be some work being done in par-
allel depending on your computer and operating system. Most likely the two compu-
tation threads are simply sharing computer resources so that they take turns using the
computer's resources. When reading your e-mail, you may or may not notice that
response is slower because resources are being shared with the virus scanning program.
Your e-mail reading program is indeed slowed down, but since humans are so much
slower than computers, any apparent slowdown is likely to be unnoticed.
EXAMPLE:
A Nonresponsive GUI
Display 19.1 contains a very simple action GUI. When the
button is clicked,
the GUI draws circles one after the other until a large portion of the window is filled
with circles. There is 1/10 of a second pause between the drawing of each circle. So, you
can see the circles appear one after the other. If you're interested in Java programming,
this can be pretty exciting for the first few circles, but it quickly becomes boring. You are
likely to want to end the program early, but if you click the close-window button, noth-
ing will happen until the program is finished drawing all its little circles. We will use
threads to fix this problem, but first let's understand this program, which does not really
use threads in any essential way, despite the occurrence of the word
"Start"
in the pro-
Thread
gram. We explain this Swing program in the next few subsections.
Thread.sleep
In Display 19.1 the following method invocation produces a 1/10 of a second pause
after drawing each of the circles:
doNothing(PAUSE);
which is equivalent to
doNothing(100);
The method
is a private helping method that does nothing except call the
doNothing
method
and take care of catching any thrown exception. So, the pause
is really created by the method invocation
Thread.sleep
Thread.sleep
Thread.sleep(100);
This is a static method in the class
that pauses whatever thread includes the
invocation. It pauses for the number of milliseconds (thousandths of a second) given
as an argument. So, this pauses the computation of the program in Display 19.1 for
100 milliseconds or 1/10 of a second.
“Wait a minute,” you may think, “the program in Display 19.1 was not supposed
to use threads in any essential way.” That is basically true, but every Java program uses
Thread
Search WWH ::




Custom Search