线程实例(龟兔赛跑)

package com.Luoking.Thread;

public class Race implements Runnable {
    //定义胜利者
    private static String winner;


    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            //如果胜利者产生了,比赛结束
            if(gameOver(i)){
                break;
            }
            if(Thread.currentThread().getName().equals("兔子")){
                try {
                    Thread.sleep(1);  //模拟兔子睡觉
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(Thread.currentThread().getName()+"走了"+i+"步");
        }

    }

    //判断是否完成比赛
    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;
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"乌龟").start();
        new Thread(race,"兔子").start();
    }

}
posted @ 2022-04-27 16:47  小罗要有出息  阅读(30)  评论(0编辑  收藏  举报