// // simple example of threaded applet in Java. // public class CounterApplet extends java.applet.Applet implements Runnable { // position of leftmost end of text to write -- hardcoded to // keep this example simple, and chosen to work reasonably // well with the size in CounterApplet.html. int messageX = 125, messageY = 95; // thread to repeatedly update and redisplay counter value. Thread countThread; int counter = 0; // ---- methods that override default applet behavior ---------- // "paint" (called to redisplay applet): display counter. public void paint(java.awt.Graphics gc) { gc.drawString("Count = " + getCounter(), messageX, messageY); } // "start" (called when browser decides to start applet -- on // initially loading the page, resizing, etc.): // if there is no counter thread, create one. public void start() { if (countThread == null) { System.out.println("starting counter thread"); countThread = new Thread(this); countThread.start(); } } // "stop" (called when browser decides to stop applet -- when // page is no longer being displayed, on resizing, etc.): // if there is a counter thread, interrupt and delete it. // (see "run" below for how the thread deals with what is // done here.) public void stop() { if (countThread != null) { System.out.println("stopping counter thread"); Thread temp = countThread; countThread = null; temp.interrupt(); } } // ---- method for Runnable interface -------------------------- // "run": // every 500 millisecs, update counter and refresh display. public void run() { // execute until stop() makes countThread null, or // until interrupted. while (countThread != null) { updateCounter(); repaint(); try { Thread.sleep(500); } catch (InterruptedException e) { return; } } } // ---- methods to update, display counter --------------------- // synchronized to avoid simultaneous access to counter // by getCounter (in applet display thread) and // updateCounter (in counter thread). synchronized private int getCounter() { return counter; } synchronized private void updateCounter() { counter++; } }