Threading an Applet
Applets are embeddable Java applications that are expected to start and stop themselves on command, possibly many times in their lifetime. A Java-enabled web browser normally starts an applet when the applet is displayed and stops it when the user moves to another page or (in theory) when the user scrolls the applet out of view. To conform to this API, we would like an applet to cease its nonessential activity when it is stopped and resume it when started again. We’ll talk about applets in Chapter 23, but it’s not really essential to know about them here. We’ll just use this as a more realistic example and as a transition to talk about our next topic, synchronization.
In this section, we will build UpdateApplet, a simple base class for an applet
that maintains a thread to automatically update its display at regular
intervals. UpdateApplet handles the
basic creation and termination of the thread in the Applet’s start() and stop() methods:
publicclassUpdateAppletextendsjava.applet.AppletimplementsRunnable{Threadthread;booleanrunning;intupdateInterval=1000;publicvoidrun(){while(running){repaint();try{Thread.sleep(updateInterval);}catch(InterruptedExceptione){System.out.println("interrupted...");return;}}}publicvoidstart(){System.out.println("starting...");if(!running)// naive approach{running=true;thread=newThread(this);thread.start();}}publicvoidstop(){System.out.println("stopping...");thread ...