Java Reference
In-Depth Information
As a final example before moving on to a different subject, let's take a look at how we could
set up the fetching of a team roster on a regular basis, so we could be sure of always having
the most recent lineup. To do this, we could just change our
run()
method so that it is an
infinite loop that would end with a
wait()
on completing each iteration. But this means that
the thread that runs the
RosterRetriever
is around all the time, which wastes resources. A
better way is to use a
Timer
object, which can be used to schedule any number of recurring
tasks like this using a single thread.
To do this, we first have to change our
RosterRetriever
class to be a particular kind of
Runnable
, the
TimerTask
. Once again, this just requires a change in the declaration of the
RosterRetriever
class, since the all-important
run()
method is common to
Thread
,
Run-
nable
, and
TimerTask
objects. So now our
RosterRetriever
is declared as:
private class RosterRetriever extends TimerTask {
We also add a
Timer
to our local state in the
StatReporterImpl
, something like:
private Timer taskTimer = new Timer(true);
Now we can use the
taskTimer
to schedule recurring runs of our
RosterRetriever
objects.
To schedule a task, we could use a method like:
void setRetrieverUpdate(long hours, RosterRetriever rr){
long millis = TimeUnit.HOURS.convert(hours, TimeUnit.MILLISECONDS);
taskTimer.schedule(rr, System.currentTimeMillis(), millis);
}
This method will take a
RosterRetriever
object and a number of hours indicating how often
we want to get an update on that object. Each
RosterRetriever
will initially be run when
added to the
taskTimer
, and then will run again every
hours
hours. Note that we have to
convert the interval from hours to milliseconds, which are the units used throughout Java; this
is made somewhat easier by using the
TimeUnit
conversion functions.
There are lots of other ways to get multiple threads running in a program, as well as ways of
querying and manipulating those threads. This is just meant to give a flavor of what can be
done. By generating lots of threads, you can have your programming doing lots of different
things at the same time, thus making better use of the computing resources that are available