/**************************************************************************/ /* Programmer: Naoki Chigai */ /* File Name: Runner.java */ /* Date: 11/14/96 */ /* Compiler: CodeWarrior IDE, version 1.7.2 */ /**************************************************************************/ [Back] [output]
import java.util.Random; class Runner extends Thread { private static final int NUMBER_OF_RUNNERS = 3; private static final int LENGTH_OF_TRACK = 10 + 1; private static final int MIN_OF_SLEEP_TIME = 50; private static final int MAX_OF_SLEEP_TIME = 1000; private static Runner[] runner; private static boolean everyoneIsStarted = false; private static boolean SomeoneReachedGoal = false; private static String winner = null; private static Random random; public void run() { while (!everyoneIsStarted) yield(); for (int i = 0; i < LENGTH_OF_TRACK; i++) { printPosition(i); try { int sleepTime = (int)(Math.round(random.nextFloat() * (MAX_OF_SLEEP_TIME - MIN_OF_SLEEP_TIME) + MIN_OF_SLEEP_TIME)); if (i + 1 >= LENGTH_OF_TRACK) { synchronized (getClass()) { if (winner == null) { winner = getName(); SomeoneReachedGoal = true; } } } else sleep(sleepTime); } catch (InterruptedException doesNotCare) { } } } private void printPosition(int position) { String pluses = ""; for (int i = 0; i < position; i++) { pluses = pluses + "+"; } System.out.println(getName() + ": " + pluses); System.out.flush(); } static public void main(String args[]) { runner = new Runner[NUMBER_OF_RUNNERS]; random = new Random(); for (int i = 0; i < NUMBER_OF_RUNNERS; i++) { runner[i] = new Runner(); runner[i].setName("Runner" + i); runner[i].setPriority(5); } for (int i = 0; i < NUMBER_OF_RUNNERS; i++) { runner[i].start(); } everyoneIsStarted = true; while (!SomeoneReachedGoal); try { sleep(2000); } catch (InterruptedException doesNotCare) { } System.out.println("Winner is " + winner + "."); } }
[Back] [output]