/** * SimpleThread2.java * This version illustrates the approved, gentle, way of stopping a thread. * Also added are the Applet class start() and stop() methods. With these * the Applet starts right away, and stops if the user leaves the page * or iconifies it. */ import java.awt.*; import java.applet.Applet; import java.awt.event.*; public class SimpleThread2 extends Applet implements ActionListener, Runnable { private TextArea ta; private Panel pnl; private Button btnGo, btnStop; private final long max = 4000; private boolean counting ; Thread calcThread = null; public void init() { ta = new TextArea(16, 50); add(ta); pnl = new Panel(); btnGo = new Button("go"); btnStop = new Button("stop"); pnl.add(btnGo); pnl.add(btnStop); add(pnl); btnGo.addActionListener(this); btnStop.addActionListener(this); } public void start() { if(calcThread == null) { calcThread = new Thread(this); calcThread.start(); } } public void stop() { if(calcThread != null) calcThread = null; } public void run() { lotsOfNumbers(max); } public void lotsOfNumbers(long biggest) { ta.setText(""); Thread running = Thread.currentThread(); for(long i = 0; i < biggest; i++) { if((i % 10) == 0) ta.append("\n"); ta.append(String.valueOf(i) ); ta.append(" "); if((i % 400) == 0) ta.setText(""); if(running != calcThread) break; } } public void actionPerformed(ActionEvent aevt) { if(aevt.getActionCommand().equals("go")) { if (calcThread == null) { calcThread = new Thread(this); calcThread.start(); } } if(aevt.getActionCommand().equals("stop")) { System.out.println("stop!!"); if(calcThread != null) { calcThread = null; System.out.println("stopped."); } } } }