学习过程观看视频:[狂神说Java]
https://www.bilibili.com/video/BV1V4411p7EF?p=3
欢迎大家支持噢,很良心的老师了!
java代码
package com.zjl;
/**
* Created by zjl
* 2020/11/16
**/
public class Race implements Runnable{
private static String winner;
public void run() {
for (int i = 0; i <= 100; i++) {
if(Thread.currentThread().getName().equals("兔子") && i%10==5){ //模拟兔子睡觉
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean b = gameOver(i); //判断游戏是否结束了
if(b == true){
break;
}
System.out.println(Thread.currentThread().getName() + "跑了" + i +"步");
}
}
private boolean gameOver(int steps){
if(winner != null) { //如果winner不为null,说明已经有人跑完100步,游戏结束,返回true
return true;
}else {
if (steps >= 100) {
winner = Thread.currentThread().getName();
System.out.println(Thread.currentThread().getName() + "赢了!!!!!!!!!");
return true;
} else {
return false;
}
}
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"乌龟").start();
new Thread(race,"兔子").start();
}
}
测试结果: