Java Reference
In-Depth Information
scanning program to finish its computation, you can go on to, say, read your e-mail while
the virus scanning program is still executing. The operating system is using threads to
make this happen. There may or may not be some work being done in parallel depending
on your computer and operating system. Most likely, the two computation 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 because 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 "Start" 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 are 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, nothing will happen until the program is finished drawing all
its little circles. We will use threads to fix this problem, but first let us understand
this program, which does not really use threads in any essential way, despite the
occurrence of the word Thread in the program. 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 doNothing is a private helping method that does nothing except call the
method Thread.sleep and take care of catching any thrown exception. So, the pause
is really created by the method invocation
Thread.sleep
Thread.sleep(100);
This is a static method in the class Thread 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.
 
Search WWH ::




Custom Search