// AnimationFun demo // code borrowed from // http://www.dgp.toronto.edu/~mjmcguff/learn/java/06-threads/ import java.applet.*; import java.awt.*; public class AnimationFun extends Applet implements Runnable // NOTE: Applet not JApplet { Thread t = null; boolean threadSuspended; int x, y; public void start() { if (t == null) { t = new Thread(this); threadSuspended = false; t.start(); } else { if (threadSuspended) // notifying the thread { threadSuspended = false; synchronized(this) { notify(); } } } } // Executed whenever the browser leaves the page containing the applet. public void stop() { threadSuspended = true; } // Executed within the thread that this applet created. public void run() { try { while (true) { // Here's where the thread does some work if (x + 10 > 250) t.interrupt(); // the interrupt method stops a timer else x += 10; if ( threadSuspended ) // thread checks to see if it should suspend itself { synchronized( this ) { while ( threadSuspended ) { wait(); } } } repaint(); t.sleep( 1000 ); // pause for 1 second } } catch (InterruptedException e) { } } public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(x, y, 40, 40); } }