import java.io.*;
import java.applet.*;
import java.awt.*;
import java.util.*;

public class CarPark extends Applet {

  /*  The Car-Park applet    by J M Bishop  January 1998
   *  ===================    Java 1.2  August 2000
   *
   * Simulates a viewpoint with two car-parks.
   * Reads and shows an image of the view.
   * Illustrates threads and a synchronized method.
   * Can be run simply in appletviewer.
   */

  Image im;
  ViewPoint view;
  Random delay = new Random();

  public void init () {

    // Get the image
      im = getImage(getCodeBase(),"reserve.jpg");
    // Ensure that the image has been received before
    // the constructor returns.
      MediaTracker tracker = new MediaTracker(this);
      tracker.addImage(im, 0);
      try { tracker.waitForID(0);}
      catch (InterruptedException e) {}
      Font f = new Font ("SanSerif",Font.PLAIN,24);
      setFont(f);

      view = new ViewPoint("View",150);
      new CarThread("West",0).start();
      new CarThread("East",300).start();
  }

  class CarThread extends Thread {
  //----------------------------

    int cars;
    int x;
    String pos;

    CarThread (String s,int n) {
      pos = s;
      x = n;
    }

    public void run () {
      while (true) {
        cars++;
        show(x,cars,pos);
        view.enter();
        try {sleep (factor(x));}
        catch (InterruptedException e) {}
      }
    }
  }

  class ViewPoint {
  //-------------

    int x;
    int cars;
    String pos;

    ViewPoint (String s,int n) {
      x = n;
      pos = s;
    }

    synchronized void enter () {
      cars++;
      show (x,cars,pos);
    }
  }

// Utilities
// ---------
  public void paint (Graphics g) {
    g.drawImage(im,0,0,this);
  }

  void show(int x, int cars, String s) {
    Graphics g = getGraphics();
    g.setColor(Color.orange);
    g.fillRect(x,300,120,50);
    g.setColor(Color.black);
    g.drawString(s+" "+cars,x+5,330);
  }

  int factor (int x) {
    return Math.abs(delay.nextInt()%5000+x);
  }

}
