龟兔赛跑

package com.peanutist.day07;

public class TestThread01 implements Runnable{
   //定义一个赢家
   public String winner;

   //重写run方法
   public void run(){
       for (int i = 1; i <= 100; i++) {
           //让兔子睡觉
           if (Thread.currentThread().getName()=="兔子"&&i>10&&i%10==0){
               try {
                   Thread.sleep(100);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              }
          }
           boolean flag = gameOver(i);
           if(flag){
               break;
          }
           System.out.println(Thread.currentThread().getName()+"-->跑了第"+i+"步");

      }
  }

   //判断游戏是否结束
   private boolean gameOver(int steps){
       if (winner!=null){
           return true;
      }
       if (steps>=100){
           winner =Thread.currentThread().getName();
           System.out.println(winner+"赢了!!!");
           return true;
      }
       return false;
  }

   public static void main(String[] args) {
       TestThread01 testThread01 = new TestThread01();

       Thread thread01 = new Thread(testThread01,"兔子");
       Thread thread02 = new Thread(testThread01,"乌龟");

       thread01.start();
       thread02.start();
  }
}

image-20210305141714620

posted on 2021-03-05 14:18  要给小八赚罐头钱  阅读(54)  评论(0)    收藏  举报