Java Reference
In-Depth Information
Figure 15.5
The main() thread blocks until thread3 guesses the correct number and dies.
Figure 15.5 shows the output of the ThreadClassDemo program right after
thread3 runs to completion. I should point out that I ran this program a dozen
times on Windows XP, and at no point did thread2 get a chance to run and
print out Goodbye.
Timer and TimerTask Classes
The java.util.Timer class is used to create a thread that executes based on a
schedule. The task can be scheduled for a single running at a specified time or
to run after a certain amount of time has elapsed, or the task can be scheduled
to run on an ongoing basis. A single Timer object can manage any number of
scheduled tasks.
Each task is created by writing a class that extends the java.util.TimerTask
class. The TimerTask class implements Runnable, but does not implement the
run() method. Your child class of TimerTask defines the run() method, and
when the task is scheduled to run, your run() method is invoked.
Let me show you a simple example to demonstrate how these two classes
are used together to create a scheduled thread. In this example, suppose that
you have a memory-intensive program that frequently allocates and frees
memory. Garbage collection is constantly running in the background, but you
can invoke the System.gc() method to attempt to force immediate garbage col-
lection. Instead of trying to conveniently place calls to System.gc() throughout
your program, you want to create a scheduled task that invokes this method
every 5 seconds. The following GCTask runs the garbage collector, and the
ensuing TimerDemo program creates a Timer and schedules the task to repeat
every 5 seconds.
Search WWH ::




Custom Search