import java.applet.*; // use AWT rather than Swing with threads, it's "safer" import java.awt.*; public class ThreadExample extends Applet implements Runnable { private Thread thread; private String displayStr; private int count; public void init() // instantiate thread here so that thread picks up where it left off if the user returns from another web page { thread = new Thread(this); } public void start() // start the thread here rather than within the init method because start executes when the user switches back to the applet's web page as well as when the web page is loaded { thread.start(); } public void stop() // stops the thread if user switches away from applet's web page { thread.suspend(); } public void destroy() { thread.stop(); thread = null; } public void paint(Graphics g) { g.drawString(displayStr, 50, 130); } // The method that will be called when you have a thread. // You must override the run method when you implement the Runnable interface public void run() { while (count < 1000) { count++; // this is the code that you're placing into the thread displayStr = new Integer(count).toString(); repaint(); try { thread.sleep(100); // wait 100 milliseconds before continuing. Don't let a thread run too fast, especially when drawing things on the screen. } catch (InterruptedException e) // required since the sleep method throws this checked exception { System.out.println(e); // if something bad occurs, print out the error } } } }