Java Reference
In-Depth Information
Example 4−5: Timer.java (continued)
synchronized(tasks) { // Only one thread can modify tasks at a time!
tasks.add(task); // Add the task to the sorted set of tasks
tasks.notify();
// Wake up the thread if it is waiting
}
}
/**
* This inner class is used to sort tasks by next execution time.
**/
static class TimerTaskComparator implements Comparator {
public int compare(Object a, Object b) {
TimerTask t1 = (TimerTask) a;
TimerTask t2 = (TimerTask) b;
long diff = t1.nextTime - t2.nextTime;
if (diff < 0) return -1;
else if (diff > 0) return 1;
else return 0;
}
public boolean equals(Object o) { return this == o; }
}
/**
* This inner class defines the thread that runs each of the tasks at their
* scheduled times
**/
class TimerThread extends Thread {
// This flag is will be set true to tell the thread to stop running.
// Note that it is declared volatile, which means that it may be
// changed asynchronously by another thread, so threads must always
// read its true value, and not used a cached version.
volatile boolean stopped = false;
// The constructor
public TimerThread(boolean isDaemon) { setDaemon(isDaemon); }
// Ask the thread to stop by setting the flag above
public void pleaseStop() { stopped = true; }
// This is the body of the thread
public void run() {
TimerTask readyToRun = null; // Is there a task to run right now?
// The thread loops until the stopped flag is set to true.
while(!stopped) {
// If there is a task that is ready to run, then run it!
if (readyToRun != null) {
if (readyToRun.cancelled) { // If it was cancelled, skip.
readyToRun = null;
continue;
}
// Run the task.
readyToRun.run();
// Ask it to reschedule itself, and if it wants to run
// again, then insert it back into the set of tasks.
if (readyToRun.reschedule())
schedule(readyToRun);
// We've run it, so there is nothing to run now
readyToRun = null;
Search WWH ::




Custom Search