Java多线程-龟兔赛跑

淡漠灬白驹的博客 / 2023-08-06 / 原文

Java多线程-龟兔赛跑

package com.alibaba;

public class TestThread003 implements Runnable{
    private String winner;

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            boolean flag = getWinner(i);
            if(flag){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"---->跑了"+i+"步");
            if(Thread.currentThread().getName().equals("兔子") && i%10 == 0 && i != 0){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean getWinner(int steps){
        if(winner != null){
            return true;
        }
        if(steps >= 100){
            winner = Thread.currentThread().getName();
            System.out.println(Thread.currentThread().getName()+"赢得了比赛!");
            return  true;
        }
        return false;
    }

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