Title: extra Threads
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

DigitalClock12.java


import java.awt.Graphics;
import java.awt.Font;
import java.util.Calendar;

public class DigitalClock12 extends java.applet.Applet
    implements Runnable {

    Font theFont = new Font("TimesRoman",Font.BOLD,24);
    Calendar theDate;
    Thread runner;

    public void start() {
        if (runner == null) {
            runner = new Thread(this);
            runner.start();
        }
    }

    public void stop() {
        if (runner != null) {
            runner = null;
        }
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (runner == thisThread) {
            repaint();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) { }
        }
    }

    public void paint(Graphics screen) {
        theDate = Calendar.getInstance();
        screen.setFont(theFont);
        screen.drawString("" + theDate.getTime(), 10, 50);
    }
}




ColorBoxes.java

The first parameter contains the number of milliseconds to wait before changing colors. The second parameter contains the size of the square. Compile this and and run it with commands like:
java ColorBoxes 50 5
java ColorBoxes 1 5
java ColorBoxes 50 12


//: ColorBoxes.java
// Using the Runnable interface
import java.awt.*;
import java.awt.event.*;

class CBox extends Canvas implements Runnable {
  private Thread t;
  private int pause;
  private static final Color[] colors = {
    Color.black, Color.blue, Color.cyan,
    Color.darkGray, Color.gray, Color.green,
    Color.lightGray, Color.magenta,
    Color.orange, Color.pink, Color.red,
    Color.white, Color.yellow
  };
  private Color cColor = newColor();
  private static final Color newColor() {
    return colors[
      (int)(Math.random() * colors.length)
    ];
  }
  public void paint(Graphics  g) {
    g.setColor(cColor);
    Dimension s = getSize();
    g.fillRect(0, 0, s.width, s.height);
  }
  public CBox(int pause) {
    this.pause = pause;
    t = new Thread(this);
    t.start();
  }
  public void run() {
    while(true) {
      cColor = newColor();
      repaint();
      try {
        t.sleep(pause);
      } catch(InterruptedException e) {}
    }
  }
}

public class ColorBoxes extends Frame {
  public ColorBoxes(int pause, int grid) {
    setTitle("ColorBoxes");
    setLayout(new GridLayout(grid, grid));
    for (int i = 0; i < grid * grid; i++)
      add(new CBox(pause));
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
  public static void main(String[] args) {
    int pause = 50;
    int grid = 8;
    if(args.length > 0)
      pause = Integer.parseInt(args[0]);
    if(args.length > 1)
      grid = Integer.parseInt(args[1]);
    Frame f = new ColorBoxes(pause, grid);
    f.setSize(500, 400);
    f.setVisible(true);
  }
} ///:~




NewRaceApplet.java


import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;



class NewRunner extends Thread {
    static  int BIG_NUMBER=  50000000;
    public int tick = 1;
    int myIndex;
    boolean yield_flag;

    NewRunner (int index, boolean yield)
    {
	  yield_flag = yield;
        myIndex = index;
    }

    public void run() {
       System.out.println(myIndex + " Start Racer ");

       while (tick < BIG_NUMBER)
		{
			tick ++;
			if (yield_flag && (tick % 500)== 0)
				yield();
		}


       System.out.println(myIndex + " Racer Finishing");
    }
}



public class NewRaceApplet extends Applet implements Runnable {

    int number = 0;
    int spacing =5;
    boolean fair = false;
    boolean yield = false;

    NewRunner[] runners;

    Thread updateThread = null;

    public void init() {
        String str;

        if (getParameter("fair") != null)
                fair = true;
        if (getParameter("yield") != null)
                yield = true;

        // We want to speed this up if the yield flag is on to
        // produce faster progress
        if (yield)
                NewRunner.BIG_NUMBER /= 10;

        str = getParameter("number");
        if (str != null)
                number = Integer.parseInt(str);
        runners = new NewRunner[number];
        spacing = (getSize().height - 100)/number;

        setBackground(Color.lightGray);

    }

    public boolean mouseDown (Event e, int x , int y)
    {
	  int priority;
        if (updateThread != null)
                return true; // Don't start the thread twice

        updateThread = new Thread(this, "Thread Race");
	  priority = Math.min(Thread.MAX_PRIORITY, number+3);
        updateThread.setPriority(priority);
        updateThread.start();

        for (int i = 0; i < number; i++) {
            runners[i] = new NewRunner(i, yield);
            if (fair)
                runners[i].setPriority(2);
            else
		  {
			priority = Math.min(Thread.MAX_PRIORITY, i+2);
                  runners[i].setPriority(priority);
		  }
        }

        for (int i=0; i < number; i++)
                runners[i].start();

        return true;
    }

    void InitialScreen(Graphics g)
    {
      String str="Click to start Race: ";
      if (fair)
          str += " fair ";
      else
          str += " unfair ";
      if (yield)
          str += " yield ";
      else
          str += " no-yield ";
      g.drawString(str, 5, 20);
    }

    void updateScreen(Graphics g) {
        int delta = NewRunner.BIG_NUMBER/600;
        for (int i = 0; i < number; i++) {
		if (runners[i] != null)
	            g.drawLine(5, 50+i*spacing,
      	         5 + (runners[i].tick)/delta, 50+i*spacing);
        }
    }


    public void paint(Graphics g) {
       InitialScreen(g);
       updateScreen(g);
    }

    public void update(Graphics g) {
        updateScreen(g);
    }


    public void run() {
       Thread myThread = Thread.currentThread();
       System.out.println("Start Updater Thread");

        while (updateThread == myThread) {
            repaint();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) { }
        }
    System.out.println("Stop Updater Thread");
    }

    public void stop() {
        for (int i = 0; i < number; i++) {
		if (runners[i] != null)
              if (runners[i].isAlive())
              {
                // We would like to terminate our runners and
                // mark allow for their cleanup in the heap manager
                runners[i].tick = NewRunner.BIG_NUMBER;
                runners[i] = null;
              }
        }
        if (updateThread != null)
		if (updateThread.isAlive())
            	updateThread = null; // Should get us out or run( )
    }




}




Last Updated: September 2, 2002 4:38 PM