import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class producer extends Applet implements Runnable {
  Font F = new Font("TimesRoman", Font.BOLD, 18);
  TextField proText= new TextField(8);
  Button proButton= new Button("P Start/Stop");
  Thread proT;
  boolean suspendp;
  String msgP="started";

  int n;                    // value in the buffer
  boolean valueSet=false;   // shows if there is a value in buffer

  public void init() {
	add(proText);
	add(proButton);
  } // init

  // put a value to the buffer
  synchronized void put(int n) {
	try {
	  while (valueSet == true) // wait until buffer is cleared
		wait();
	  this.n = n;
	  proText.setText("  "+n);
	  valueSet = true; // a new value is put to buffer
	  repaint();
	  notify();
	} catch (InterruptedException e) {  }
  } //put

  // read a value from buffer (consumers use this method)
  synchronized int get() {
	try {
	  while (valueSet == false) // wait until a value is put to buffer
		wait();
	  valueSet = false; // the value is read from buffer so buffer is empty
	  notify();
	} catch(InterruptedException e)  { }
	return n;
  }//get

  public void run() {
	int i = 1;
	while (true)  {
	  if (!suspendp)  // if producer is not suspended
					  //  go on to produce numbers
		put(i++);
	  try { Thread.sleep(500); }
	  catch (InterruptedException e) { }
	 }
  } // run method

  public void start() {
	if (proT == null) {
	  proT = new Thread(this);
	  proT.start();
	}
  }   // start method

  public void stop() {
	if (proT != null) {
	  proT.stop();
	  proT=null;
	}
  } // stop method

  // Now handle button events for producer
  public boolean action(Event evtObj, Object arg) {
	if(evtObj.target instanceof Button) {
	  if(arg.equals("P Start/Stop")) {
		if (suspendp)  { // suspended so start it again
		  msgP= "started";
		  suspendp=false;
		  repaint();
		}
		else { // started so now suspend it
		  msgP="suspended";
		  suspendp=true;
		  repaint();
		}
	  }
	  return true;
	}
	return false;
  }

  public void paint(Graphics g) {
	g.setFont(F);
	g.drawString("PRODUCER",60,60);
	g.drawString("Producer is "+msgP,10,125);
  }

} // end of applet