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("兔子") && i % 10 == 0) {
try {
Thread.sleep(10);
} 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 is"+winner);
return true;
}
return false;
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"乌龟").start();
new Thread(race,"兔子").start();
}
}
龟兔赛跑初
最新推荐文章于 2024-11-04 22:26:34 发布
这篇文章详细描述了一个Java程序,实现了两个线程‘兔子’和‘乌龟’的竞赛,通过`Runnable`接口模拟赛跑过程。每个线程每跑10步会暂停1秒,当某线程完成100步时,宣布胜者并结束比赛。核心是`run()`方法和`gameover()`函数的交互。
摘要由CSDN通过智能技术生成