// File: Race2.java (Module 12) // // Author: Rahul Simha // Created: Nov 17, 1998 // // A simple simulation with threads. import java.awt.*; import java.awt.event.*; class NewFrame extends Frame { Canvas c; public NewFrame () { // Frame properties. this.setTitle ("Dog Race"); this.setBackground (Color.cyan); this.setResizable (true); this.setSize (600,200); // Quit button. Panel p = new Panel (); Button quitb = new Button ("QUIT"); quitb.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { System.exit (0); } } ); p.add (quitb); // Pressing "start" calls race() Button startb = new Button ("START"); startb.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { race (); } } ); p.add (startb); this.add (p, BorderLayout.SOUTH); // A canvas to draw the results. c = new Canvas(); c.setBackground (Color.white); this.add (c, BorderLayout.CENTER); this.setVisible (true); } void race () { Dimension D = c.getSize (); // Finish-line is at the right end of the canvas. int finish_line = D.width; // Create two dog instances with different ID's. Dog d1 = new Dog (1, c); Dog d2 = new Dog (2, c); // Create a Thread instance for each dog. // Note: the class Dog must implement the // Runnable interface. Thread d1_thread = new Thread (d1); Thread d2_thread = new Thread (d2); // Start running the threads. // ("start" is a method in Thread). d1_thread.start(); d2_thread.start(); } } class Dog implements Runnable { public int position = 20; // Starting position. int ID; // An ID. Canvas c; // The canvas on which to draw. public Dog (int ID, Canvas c) { this.ID = ID; this.c = c; // Draw ID on canvas. Graphics g = c.getGraphics (); g.drawString (""+ID, 5, 20*ID+8); } public void move () { // Move a random amount. int new_position = position + (int) UniformRandom.uniform (50,100); // Draw new position. Graphics g = c.getGraphics (); int size = new_position - position; g.fillRect (position, 20*ID, size, 10); position = new_position; } // Must implement this method to implement // the Runnable interface. public void run () { // Compute the finish line distance. int finish_line = c.getSize().width; // While not complete... while (position < finish_line) { // Sleep try { Thread.sleep ((int)UniformRandom.uniform (300,600)); } catch (InterruptedException e) { System.out.println (e); } // Move. move (); } } } public class Race2 { public static void main (String[] argv) { NewFrame nf = new NewFrame (); } }