Spectators
We have to give the spectators access to the current standings in the race, and we want them to do so frequently and regularly. We'll start with a Spectator class, which is Runnable and has a one-line run() method that retrieves a String describing the position of all the racers:
public void run() { String result = getEvent().getStatus().getPositionsString(); }
Don't worry about how the String is generated; we'll get into that in a moment. But note that nothing here handles repetition or timing; that's all handled with another new class called ScheduledExecutorService. Using this class, a pool of threads can be set to run repeatedly at regular intervals after an optional initial delay:
ScheduledExecutorService spectatorPool = Executors.newScheduledThreadPool(getNumSpectators()); ... //Create spectators for(int i = 0; i < getNumSpectators(); ++i) { transientSpectator = new Spectator(this); spectatorPool.scheduleAtFixedRate(transientSpectator, 0, 1000, TimeUnit.MILLISECONDS); }
The above code creates a sufficiently large thread pool and then creates and adds Spectators, starting them with a delay of 0 and rerunning each once a second.
NOTE
If the thread pool is smaller than the number of Runnables you submit, it's likely that only those Runnables submitted first will see regular attention, unless they die or block, making room for the later Runnables. Also, there's no guarantee here that a Spectator will be run exactly once a second, but even so this class is a solid replacement for the old Timer class.