1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| public class RaceTest implements Runnable {
private static String winner = null;
@Override public void run() { for (int i = 1; i <= 101; i++) { boolean flag = gameOver(i); if (flag) { break; } if(Thread.currentThread().getName().equalsIgnoreCase("Rabbit")){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "Run " + i + " step."); } }
private boolean gameOver(int steps) { if (winner != null) { return true; } else { if (steps >= 100) { winner = Thread.currentThread().getName(); System.out.println("Winner is: " + winner); return true; } } return false; } }
class M {
public static void main(String[] args) { RaceTest raceTest = new RaceTest(); new Thread(raceTest, "Rabbit").start(); new Thread(raceTest, "Tortoise").start();
} }
|