Java Reference
In-Depth Information
We can get exactly the same results in a slightly different way that also gives us more flex-
ibility in how we run our background gathering of rosters. If we make the RosterRetriever
implement the interface Runnable , we can create threads that will run instances of the class.
Changing the RosterRetriever class for this sort of approach is easy; all we have to do is
change the class declaration from:
private class RosterRetriever extends Thread {
to:
private class RosterRetriever implements Runnable {
The Runnable interface requires the implementation of a single method, run() , which takes
no arguments and returns void. Fortunately, we already have such a method, so we don't have
to add anything. This isn't surprising, as the reason for the Runnable interface is to allow
classes implementing that interface to be executed in separate threads.
We do need to change the way we start off the RosterRetriever object. Rather than just call-
ing start() , which the class inherited from Thread when it was an extension of that class,
we need to create a Thread object, handing a RosterRetriever object into the constructor
for the Thread . We can then start() the Thread object. So our startRosterLookup would
now look like:
private RosterRetriever startRosterLookup(String fromHost, String team){
RosterRetriever getter = new RosterRetriever(fromHost, team);
Thread rrThread = new Thread(getter);
rrThread.start();
return getter;
}
This has the same result as our earlier implementation, but we can now do other things to con-
trol the thread use in our program. For example, rather than allocating a new thread every time
we want to run a RosterRetriever , we could have a pool of threads and take a thread from
that pool if one is available or wait until such a thread was returned to the pool before fetching
a remote roster. This would allow us to limit the number of threads that are taken up in this
kind of background task.
Search WWH ::




Custom Search