多线程龟兔赛跑--Runnable版本

Runnable实现龟兔赛跑

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);//兔子睡觉了zzzz
                } 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();

    }
}
posted @ 2021-01-16 15:18  Hlooc  阅读(75)  评论(0编辑  收藏  举报