Nothing wrong with that isReset
, but won't this loop just call it over and over and over (and over and over...)?
while (true) {
for (i=0; i < alg.length; i++)
if (execPanel[i].isReset()) {
alg[i].terminate();
createProgram(i);
alg[i].start();
execPanel[i].unreset();
}
}
If nothing else, you can slap a Thread.yield()
in there to force the thread to give up its time slice regularly so it doesn't hog the CPU.
Better would be to ditch the polling and instead use a listener-based approach. Allow the execPanel
s to notify listeners when they are reset instead of having one loop repeatedly ask them if they are reset. This code is the equivalent of "Are we there yet? Are we there yet? Are we there yet?"
You might also see listeners referred to as observers. If you look around for more information about this design pattern a lot of good information will turn up using both terms.
Example
Here's how you might rewrite your code to use the listener concept. I apologize for any errors in this code, I haven't compiled it. Hopefully the ideas are clear despite any errors I might have in the code.
If the code doesn't make sense right away, check out my links above. Or you can play around with EventListener
s, which you'll use all the time when you do Swing GUI programming.
public class SkaExecutionPanel {
// Anybody who wants to be told when a panel is reset will implement
// this interface and call addListener().
public interface Listener {
void panelReset(SkaExecutionPanel panel);
}
// Each panel needs to maintain an internal list of listeners.
private List<Listener> listeners = new ArrayList<Listener>();
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
public void reset() {
/* Do your thing. */
// When something happens that the listeners will care about, such as a
// call to reset() in this case, you iterate through the list and tell
// each one what's happened.
for (Listener listener: listeners) {
listener.panelReset(this);
}
}
}
public class SkaTest {
public static void main(String args[]) {
/* Snippety snip. */
for (i=0; i < alg.length; i++) {
// Here we need to tell the execPanels that we want to do something
// whenever somebody calls reset() on them. We will add a listener
// to each panel that does the terminate/createProgram/start dance.
// This way we don't have to ask the panels when they are reset;
// instead they will tell us when that happens.
execPanel[i].addListener(new SkaExecutionPanel.Listener() {
final int index = i;
public void panelReset(SkaExecutionPanel panel) {
alg[index].terminate();
createProgram(index);
alg[index].start();
execPanel[index].unreset();
}
});
}
}
}