多线程模拟龟兔赛跑游戏

多线程模拟龟兔赛跑游戏

package com.zuoyan.lesson01;

/**
 * 多线程模拟龟兔赛跑游戏
 */
public class Race implements Runnable{
    
    

    private String winner;

    @Override
    public void run() {
    
    

        for (int i = 0; i <= 100; i++) {
    
    

            //模拟兔子睡觉
            if ("兔子".equals(Thread.currentThread().getName()) && i % 10 == 0) {
    
    
                try {
    
    
                    //线程休息10毫秒
                    Thread.sleep(10);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }

            if (gameOver(i)) {
    
    
                break;
            }

            //获取当前线程名称
            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 + "赢得了比赛!");
                return true;
            }
        }
        return false;
    }

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

猜你喜欢

转载自blog.csdn.net/weixin_41692833/article/details/112800968