Threads in Applets
Applets are embeddable Java applications that are expected to be able to start and stop themselves on command. Applets may be asked to start and stop themselves any number of times. 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 the semantics of the API, we would like an applet to cease its nonessential activity when it is stopped and resume it when started again. (If you’re not familiar with applets, you may want to take a look at Chapter 20, at this point.)
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. Although
we’re building an applet here, the general technique is
important for all threaded applications.
UpdateApplet handles the basic starting and
stopping behavior for us:
//file: UpdateApplet.java public class UpdateApplet extends java.applet.Applet implements Runnable { private Thread updateThread; int updateInterval = 1000; public void run( ) { while ( updateThread != null ) { try { Thread.sleep( updateInterval ); } catch (InterruptedException e ) { return; } repaint( ); } } public void start( ) { if ( updateThread == null ) { updateThread = new Thread(this); updateThread.start( ); } } public void stop( ) { if ( updateThread != null ) { Thread runner = updateThread; updateThread = null; ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access