/**
 * SimpleThread1.java
 * This version uses a separate thread to carry out the number generation. 
 * This version sets the string to null every 1000 numbers.
 * Note the superior performance ofver NoThread.java
 * Another point to notice is that this program calls stop() on the
 * thread to stop it. This is no longer considered good form.
 * stop() kills a thread and may leave things hanging (open files for example).
 */
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class SimpleThread1 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 run() {
      lotsOfNumbers(max);
   }

   public void lotsOfNumbers(long biggest) {
      ta.setText("");
      for(long i = 0; i < biggest; i++) {
         if((i % 10) == 0) ta.append("\n");
         ta.append(String.valueOf(i) );
         ta.append(" ");
         if( calcThread == null ) break;
         if((i % 1000) == 0) ta.setText("");
      }
   }

   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.stop();   // the stop() method is deprecated
            calcThread = null;
         }
      }
   }
}