ThreadsExample

ThreadsExample - for(int i = 0; i < NUM_RACERS;...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
/* * File: ThreadsExample.java * ------------------------- * This programs shows an example of threads to simulate running a race. */ import acm.program.*; import acm.graphics.*; import java.awt.event.*; import javax.swing.*; i public class ThreadsExample extends GraphicsProgram { p public void run() { racers = new RacingSquare[NUM_RACERS]; finished = new boolean[NUM_RACERS]; threads = new Thread[NUM_RACERS]; t // finish line add(new GLine(510, 0, 510, 400)); a add(new JButton("Start!"), SOUTH); addActionListeners(); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Start!")) {
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: for(int i = 0; i < NUM_RACERS; i++) { // remove the racer, if it previously existed if (racers[i] != null) { remove(racers[i]); } // create new racer racers[i] = new RacingSquare(i, finished); add(racers[i], 10, 10 + (40 * i)); a // send the new racer along their way // (on a separate thread) threads[i] = new Thread(racers[i]); threads[i].start(); } } } /* private instance variables */ private Thread threads; private RacingSquare racers; private boolean finished; p /* constants */ private static final int NUM_RACERS = 10; }...
View Full Document

Ask a homework question - tutors are online