522 Part II: The Java Library
TheObservableclass and theObserverinterface allow you to implement sophisticated
program architectures based on the document/view methodology. They are also useful in
multithreaded situations.
Timer and TimerTask
An interesting and useful feature offered byjava.utilis the ability to schedule a task for
execution at some future time. The classes that support this areTimerandTimerTask. Using
these classes, you can create a thread that runs in the background, waiting for a specific
time. When the time arrives, the task linked to that thread is executed. Various options
allow you to schedule a task for repeated execution, and to schedule a task to run on a
specific date. Although it was always possible to manually create a task that would be
executed at a specific time using theThreadclass,TimerandTimerTaskgreatly simplify
this process.
TimerandTimerTaskwork together.Timeris the class that you will use to schedule
a task for execution. The task being scheduled must be an instance ofTimerTask. Thus, to
schedule a task, you will first create aTimerTaskobject and then schedule it for execution
using an instance ofTimer.
TimerTaskimplements theRunnableinterface; thus, it can be used to create a thread
of execution. Its constructor is shown here:
TimerTask( )
TimerTaskdefines the methods shown in Table 18-8. Notice thatrun( )is abstract, which
means that it must be overridden. Therun( )method, defined by theRunnableinterface,
contains the code that will be executed. Thus, the easiest way to create a timer task is to extend
TimerTaskand overriderun( ).
Once a task has been created, it is scheduled for execution by an object of typeTimer.
The constructors forTimerare shown here:
Timer( )
Timer(booleanDThread)
Timer(StringtName)
Timer(StringtName, booleanDThread)
The first version creates aTimerobject that runs as a normal thread. The second uses a
daemon thread ifDThreadistrue. A daemon thread will execute only as long as the rest of
the program continues to execute. The third and fourth constructors allow you to specify a
name for theTimerthread. The methods defined byTimerare shown in Table 18-9.
Method Description
boolean cancel( ) Terminates the task. Returnstrueif an execution of the task is
prevented. Other wise, returnsfalse.
abstract void run( ) Contains the code for the timer task.
long scheduledExecutionTime( ) Returns the time at which the last execution of the task was
scheduled to have occurred.
TABLE 18-8 The Methods Defined byTimerTask