import java.awt.*; import java.applet.*; import Counter; public class MultipleThreads extends Applet { Counter thread1; Counter thread2; String displayStr; Font font; int position; public void init() { font = new Font("TimesRoman", Font.PLAIN, 72); setFont(font); displayStr = ""; position = 120; thread1 = new Counter(this, true); thread2 = new Counter(this, false); } public void start() { if (thread1.isAlive()) thread1.resume(); else thread1.start(); if (thread2.isAlive()) thread2.resume(); else thread2.start(); } public void stop() { thread1.suspend(); thread2.suspend(); } public void destroy() { thread1.stop(); thread2.stop(); } public void paint(Graphics g) { g.drawString(displayStr, 50, position); } synchronized public void SetDisplayStr(String str, int pos) { displayStr = str; position = pos; repaint(); } } public class Counter extends Thread { MultipleThreads applet; boolean forward; int count; int increment; int end; int position; Counter(MultipleThreads applet, boolean forward) { this.applet = applet; this.forward = forward; } public void run() { InitCounter(); DoCount(); } protected void InitCounter() { if (forward) { count = 0; increment = 1; end = 1000; position = 120; } else { count = 1000; increment = -1; end = 0; position = 180; } } protected void DoCount() { while (count != end) { count = count + increment; String str = String.valueOf(count); applet.SetDisplayStr(str, position); try { sleep(100); } catch (InterruptedException e) { } } } }