/** * Adapted from The Java Tutorial * Second Edition by Campione, M. and * Walrath, K.Addison-Wesley 1998 */ class SelfishRunner extends Thread { private int tick = 1; private int num; public SelfishRunner(int num) { this.num = num; } public void run() { while (tick < 400000) { tick++; if ((tick % 50000) == 0) System.out.println("Thread #" + num + ", tick = " + tick); } } } class PoliteRunner extends Thread { private int tick = 1; private int num; public PoliteRunner(int num) { this.num = num; } public void run() { while (tick < 400000) { tick++; if ((tick % 50000) == 0){ System.out.println("Thread #" + num + ", tick = " + tick); yield(); } } } } public class RaceTest { private final static int NUMRUNNERS = 2; public static void main(String[] args) { System.out.println("Selfish Runner:"); SelfishRunner[] runners = new SelfishRunner[NUMRUNNERS]; for (int i = 0; i < NUMRUNNERS; i++) { runners[i] = new SelfishRunner(i); runners[i].setPriority(2); } for (int i = 0; i < NUMRUNNERS; i++) runners[i].start(); try{ Thread.sleep(10000); } catch(InterruptedException e){ } for (int i = 0; i < NUMRUNNERS; i++) runners[i]=null; System.out.println("Polite Runner:"); PoliteRunner[] runners2 = new PoliteRunner[NUMRUNNERS]; for (int i = 0; i < NUMRUNNERS; i++) { runners2[i] = new PoliteRunner(i); runners2[i].setPriority(2); } for (int i = 0; i < NUMRUNNERS; i++) runners2[i].start(); } }