home *** CD-ROM | disk | FTP | other *** search
/ Java 1996 August / Java - Summer 1996.iso / rockridge / java / threads / classes / RaceApplet.java < prev    next >
Encoding:
Java Source  |  1995-11-13  |  1.8 KB  |  75 lines

  1.  
  2. import browser.Applet;
  3. import awt.*;
  4.  
  5. class RaceApplet extends Applet implements Runnable {
  6.  
  7.     final static int NUMRUNNERS = 2;
  8.     final static int SPACING = 20;
  9.  
  10.     Runner runners[] = new Runner[NUMRUNNERS];
  11.  
  12.     Thread updateThread;
  13.  
  14.     public void init() {
  15.     String raceType = getAttribute("type");
  16.     for (int i = 0; i < NUMRUNNERS; i++) {
  17.         runners[i] = new Runner();
  18.         if (raceType.compareTo("unfair") == 0)
  19.             runners[i].setPriority(i+1);
  20.         else
  21.             runners[i].setPriority(2);
  22.         }
  23.         if (updateThread == null) {
  24.             updateThread = new Thread(this, "Thread Race");
  25.             updateThread.setPriority(NUMRUNNERS+1);
  26.         }
  27.     }
  28.  
  29.     public void mouseDown(int x, int y) {
  30.     if (!updateThread.isAlive())
  31.             updateThread.start();
  32.     for (int i = 0; i < NUMRUNNERS; i++) {
  33.         if (!runners[i].isAlive())
  34.             runners[i].start();
  35.     }
  36.     }
  37.  
  38.     public void paint(Graphics g) {
  39.         g.setForeground(Color.lightGray);
  40.         g.fillRect(0, 0, width, height);
  41.         g.setForeground(Color.black);
  42.         for (int i = 0; i < NUMRUNNERS; i++) {
  43.         int pri = runners[i].getPriority();
  44.         g.drawString(new Integer(pri).toString(), 0, (i+1)*SPACING);
  45.     }
  46.         update(g);
  47.     }
  48.  
  49.     public void update(Graphics g) {
  50.         for (int i = 0; i < NUMRUNNERS; i++) {
  51.         g.drawLine(SPACING, (i+1)*SPACING, SPACING + (runners[i].tick)/1000, (i+1)*SPACING);
  52.     }
  53.     }
  54.  
  55.     public void run() {
  56.         while (updateThread != null) {
  57.             repaint();
  58.             updateThread.sleep(10);
  59.         }
  60.     }    
  61.  
  62.     public void stop() {
  63.     for (int i = 0; i < NUMRUNNERS; i++) {
  64.         if (runners[i].isAlive()) {
  65.             runners[i].stop();
  66.             runners[i] = null;
  67.         }
  68.         }
  69.     if (updateThread.isAlive()) {
  70.             updateThread.stop();
  71.             updateThread = null;
  72.     }
  73.     }
  74. }
  75.