Java多线程-龟兔赛跑

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();
    }
}

posted @   淡漠灬白驹  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示