// add Thread priorities import java.awt.*; import java.awt.event.*; import javax.swing.*; class NewFrame extends JFrame { // For drawing the race results. JPanel drawingArea; public NewFrame () { // Frame properties. this.setTitle ("Dog Race"); this.setResizable (true); this.setSize (600,200); Container cPane = this.getContentPane(); cPane.setLayout (new BorderLayout()); // Quit button. JPanel p = new JPanel (); JButton quitb = new JButton ("QUIT"); quitb.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent a) { System.exit (0); } } ); p.add (quitb); // Pressing "start" calls race() JButton startb = new JButton ("START"); startb.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent a) { race (); } } ); p.add (startb); // Now add the panel to the frame. cPane.add (p, BorderLayout.SOUTH); // A JPanel to draw the results. drawingArea = new JPanel(); drawingArea.setBackground (Color.white); cPane.add (drawingArea, BorderLayout.CENTER); this.setVisible (true); } void race () { // Create two dog instances with different ID's. Dog d1 = new Dog (1, drawingArea, 3, 6, this); Dog d2 = new Dog (2, drawingArea, 3, 6, this); Dog.startRace(); d1.setPriority(Thread.NORM_PRIORITY); d2.setPriority(Thread.NORM_PRIORITY+3); d1.start(); d2.start(); } } class Dog extends Thread { public int position = 20; // Starting position. int ID; // An ID. JPanel drawingArea; // The panel on which to draw. int minNap, maxNap; NewFrame f; static boolean over; public Dog (int ID, JPanel drawingArea, int min, int max, NewFrame f) { this.f = f; minNap = min; maxNap = max; this.ID = ID; this.drawingArea = drawingArea; // Draw ID on panel. Graphics g = drawingArea.getGraphics (); g.drawString (""+ID, 5, 20*ID+8); } public static void startRace() { over = false; } public void nap() { try { Thread.sleep (minNap + (int)(Math.random()*(maxNap-minNap))); } catch (InterruptedException e) { System.out.println (e); } } public void move () { // Move a random amount. int newPosition = position + (int) (50 + 50*Math.random()); // Draw new position. Graphics g = drawingArea.getGraphics (); int size = newPosition - position; g.fillRect (position, 20*ID, size, 10); position = newPosition; } // Must implement run() to satisfy Runnable interface public void run () { // Compute the finish line distance. int finishLine = drawingArea.getSize().width; // While not complete... while ((position < finishLine) && !raceFinished(false, ID)) { nap(); move (); } if (position >= finishLine) raceFinished(true, ID); } public boolean raceFinished(boolean set, int caller) { if (set) over = true; return over; } } public class Race5 { public static void main (String[] argv) { NewFrame nf = new NewFrame (); } }