I have an abstract class as follows:
abstract class Grapher implements Runnable{
... member variables...
Timer timer;
boolean Done;
public void run(){
Done = false;
timer.start();
while(!Done){}
}
public void Grapher(){ //create graph}
...
}
The idea is that I want to have this abstract thread that creates a graph. I then want to extend this class to provide the implementation of what data that should be plotted on the graph. For example:
class RandomGraph extends Grapher{
ActionListener taskPerformer;
public RandomGraph(){
timer = new Timer(1000, taskPerformer);
taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// generate random data and add it to the graph data;
// if ... Done = true
}
};
}}
This should then plot random data to the graph. The problem I’m having is that I’m getting completely stuck in the while(!done) loop. Putting System.out.printlns inside the actionListener tell me the timer does not seem to be working as nothing appears on the console.
Am I being stupid for using threads at all? I thought it might be a good idea If I want the graph to plot data every few milliseconds.
You’re passing
nullto theTimerconstructor — you need to initializetaskPerformerfirst 🙂To address your bigger question: No, you’re not stupid for using threads. However, I question your use of an abstract class at all here. What you really want is an interface
Grapherdescribing an object that draws graphs, then a concrete subclass ofRunnable(say,GrapherRunner) that sets up the timer, then delegates to a grapher to do the work.(In OO-speak, this means using composition rather than inheritance.)