The Observable class and the Observer interface 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 by java.util is the ability to schedule a task for
execution at some future time. The classes that support this are Timer and TimerTask. 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 the Thread class, Timer and TimerTask greatly simplify
this process.
Timer and TimerTask work together. Timer is the class that you will use to schedule
a task for execution. The task being scheduled must be an instance of TimerTask. Thus, to
schedule a task, you will first create a TimerTask object and then schedule it for execution
using an instance of Timer.
TimerTask implements the Runnable interface; thus, it can be used to create a thread
of execution. Its constructor is shown here:
TimerTask( )
TimerTask defines the methods shown in Table 18-8. Notice that run( ) is abstract, which
means that it must be overridden. The run( ) method, defined by the Runnable interface,
contains the code that will be executed. Thus, the easiest way to create a timer task is to extend
TimerTask and override run( ).
Once a task has been created, it is scheduled for execution by an object of type Timer.
The constructors for Timer are shown here:
Timer( )
Timer(boolean DThread)
Timer(String tName)
Timer(String tName, boolean DThread)
The first version creates a Timer object that runs as a normal thread. The second uses a
daemon thread if DThread is true. 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 the Timer thread. The methods defined by Timer are shown in Table 18-9.
boolean cancel( )
Terminates the task. Returns true if an execution of the task is
prevented. Other wise, returns false.
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 by TimerTask
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks