多线程模拟龟兔赛跑(兔子睡觉)
作者:互联网
public class race implements Runnable{
//只能有一个赢家,所以这里winner是静态属性
private static String winner;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if(Thread.currentThread().getName().equals("兔子")){
try {
//当兔子在跑时,就让他休息1毫秒
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 steps){
if(winner!=null){
return true;
}{
if(steps>=99){
winner = Thread.currentThread().getName();
System.out.println(winner+"赢了!");
return true;
}
}return false;
}
public static void main(String[] args) {
new Thread(new race(),"兔子").start();
new Thread(new race(),"乌龟").start();
}
}
标签:赛跑,龟兔,return,currentThread,Thread,getName,winner,new,多线程 来源: https://blog.csdn.net/Timooo_/article/details/121719992