11.5 Summary
In this chapter, we've looked at various ways in
which tasks may be scheduled in the future. The simplest way to do
this is to use the java.util.Timer class, which
can run instances of a special class (the
TimerTask class) at a point in the future,
repeating the task if necessary. Each instance of a timer is a single
thread; that thread can handle multiple tasks but long-running tasks
may need their own thread (and consequently their own timer).
The javax.swing.Timer class is functionally
similar, except that it ensures that tasks are run on the
event-dispatching thread so that they may safely access Swing
components. However, the javax.swing.Timer class
has a fixed time schedule for all the tasks it runs; tasks that have
different scheduling needs require different instances of the timer.
Finally, the ScheduledThreadPoolExecutor class
provides a more flexible (but more complex) interface to task
scheduling. Because it uses a thread pool, it can be more efficient
when running a lot of tasks simultaneously. It also allows you to
poll for task status or to use generic Runnable
objects as your task.
The key benefit of task executors and timers is that they free you
from having to worry about thread-related programming for your tasks:
you simply feed the task to the timer or executor and let it worry
about the necessary thread controls. This makes the code that you
write that much simpler.
11.5.1 Example Classes
Here are the class names and Ant targets for the examples in this
chapter:
|
Description
|
Main Java class
|
Ant target
|
|---|
|
URL Monitor with java.util.Timer class
|
javathreads.examples.ch11.example1.URLMonitor URL1 URL2
...
|
ch11-ex1
| |
Type Tester with Timer animation
|
javathreads.examples.ch11.example2.SwingTypeTester
|
ch11-ex2
| |
URL Monitor with scheduled executor
|
javathreads.examples.ch11.example3.URLMonitor URL1 URL2
...
|
ch11-ex3
| |
URL Monitor with timeout
|
javathreads.examples.ch11.example4.URLMonitor URL1 URL2
...
|
ch11-ex4
|
The ant property to specify the URL is:
<property name="hostlist" value="http://www.ora.com/"/>
Unfortunately, Ant offers no way to specify multiple hostnames. If
you want to try a URL monitor with more than one URL, you must
execute the class directly.
|