欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java多线程实现龟兔赛跑

程序员文章站 2022-05-02 10:10:00
...
package com.zhang.lesson.ThreadDenmon;
public class Race implements Runnable {
   private static  String winner;
   
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (Thread.currentThread().getName().equals("兔子")){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            boolean flag=gameover(i);
            if (flag){
                break;
            }
            System.out.println(Thread.currentThread().getName()+ ">>>"+ "跑了" +i +"步");
        }

    }
    private boolean gameover(int stpe) {
        if (winner != null) {
            return true;
        }{
            if (stpe==100){
                winner=Thread.currentThread().getName();
                System.out.println("winnner is "+ winner);
            }
        }
        return false;
    }
    public static void main(String[] args) {
        Race race =new Race();

        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }


}

运行结果:
java多线程实现龟兔赛跑