// A Working Counting Applet - by Derek Molloy

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class CounterApplet extends Applet implements ActionListener
{
	private Button start, stop, toggle;
	private TextField countField1, countField2;
	private Counter theCounter1, theCounter2;

	public void init() 
	{
	  countField1 = new TextField(10);
	  countField2 = new TextField(10);
	  this.add(countField1);
	  this.add(countField2);

	  start = new Button("Start");
	  start.addActionListener(this);
	  this.add(start);

	  stop = new Button("Stop");
	  stop.addActionListener(this);
	  this.add(stop);

	  toggle = new Button("Toggle");
	  toggle.addActionListener(this);
	  this.add(toggle);

	  this.theCounter1 = new Counter(countField1, 100, 0);
	  this.theCounter2 = new Counter(countField2, 200, 50);
	}
	
	public void actionPerformed(ActionEvent e) 
	{
	  if (e.getSource().equals(start))
	  {
	    this.theCounter1.start();
	    this.theCounter2.start();
	  }
	  else if (e.getSource().equals(stop))
	  {
	    this.theCounter1.stopCounter();
	    this.theCounter2.stopCounter();
	  }
	  else if (e.getSource().equals(toggle))
	  {
	    this.theCounter1.toggleCounter();
	    this.theCounter2.toggleCounter();
	  }
	}
} 



class Counter extends Thread
{
	private int count, delay;
	private boolean running = true, paused = false;
	private TextField theField;

	
	public Counter(TextField t, int delay, int startValue)
	{
	  this.theField = t;
	  this.count = startValue;
	  this.delay = delay;
	}

	public void run() 
	{
	  while (running) 
	  {
	    theField.setText("Count: "+this.count++);
	    try 
	    { 
	      Thread.currentThread().sleep(this.delay); 

	      synchronized(this) {
                    while (paused)
                        wait();
              }
	    } 
	    catch (InterruptedException e)
	    {  
		theField.setText("Interrupted!");
		this.stopCounter();
	    }   
	  }
	}

	public int getCount() { return count; }

	public void stopCounter() { this.running = false; }

	public synchronized void toggleCounter()
	{ 
	  this.paused = !this.paused; 
	  if (!this.paused) notify();
	}
}
