import java.applet.Applet; public class Duke extends Thread { //---------------------------------------------------- /** Duke is a Thread that has knowledge of the parent * applet (highly coupled) and thus, may call the * parent's repaint method. Duke is mainly * responsible for changing an index value into an * image array. */ public static final int SUSPEND = 1; public static final int STOP = 2; public static final int RUN = 0; private int state = RUN; private int tumbleDirection; private int index = 0; private int numImages; private Applet parent=null; public Duke(int tumbleDirection, int numImages, Applet parent) { this.tumbleDirection = tumbleDirection; this.numImages = numImages; this.parent = parent; } public int getIndex() { return index; } //-------------------------------------------------- /** Public method to permit setting a flag to * stop or suspend the thread. State is monitored * through corresponding checkState method. */ public synchronized void setState(int state) { this.state = state; if (state==RUN) notify(); } //-------------------------------------------------- /** Returns the desired state (RUN, STOP, SUSPEND) * of the thread. If the thread is to be * suspended, then the thread method wait is * continuously called until the state is changed * through the public method setState. */ private synchronized int checkState() { while (state==SUSPEND) { try { wait(); } catch (InterruptedException e) {} } return state; } //---------------------------------------------------- /** The variable index (into image array) is * incremented once each time through the while * loop, call repaint, and pauses for a moment. Each * time through the loop the state (flag) of the * thread is checked. */ public void run() { while ( checkState()!=STOP) { index += tumbleDirection; if (index < 0) index = numImages - 1; if (index >= numImages) index = 0; parent.repaint(); try { Thread.sleep(100); } catch (InterruptedException e) { break; } // break while loop } } }