模拟龟兔赛跑
一场比赛中的每一个参赛者都是一个线程 乌龟 兔子 青蛙....
谁先跑完1000步就算赢了, 但是兔子每跑10步休息10ms
只要有人赢了游戏就结束了
package test;
public class Test3 implements Runnable {
private String winner;
@Override
public void run() {
for(int i=1;i<=1000;i++){
if("兔子".equals(Thread.currentThread().getName()) && i%10==0){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if("青蛙".equals(Thread.currentThread().getName()) && i%100==0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"正在跑第"+i+"步");
if(check(i)){
break;
}
}
}
public boolean check(int steps){
if(winner!=null){
return true;
}else if(steps==1000){
winner = Thread.currentThread().getName();
return true;
}
return false;
}
public static void main(String[] args) {
Test3 racer = new Test3();
Thread th1 = new Thread(racer,"兔子");
Thread th2 = new Thread(racer,"乌龟");
Thread th3 = new Thread(racer,"青蛙");
th1.start();
th2.start();
th3.start();
}
}