题目要求:需求: 乌龟和兔子赛跑总赛程100m, 兔子的速度是10m/s, 乌龟的速度是5m/s.乌龟和兔子都是每跑完10米输出一次结果, 当兔子跑到70米的时候休息2s ,编程模拟比赛过程
public void runTest() {
Thread t1 = new Thread("小乌龟") {
public void run() {
int count = 0;
while(count<100) {
try {
//方便在控制台上查看
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count +=5;
//每10米打印一次
if (count%10==0) {
System.out.println("小乌龟跑了"+count+"米");
}
}
}
};
Thread t2 = new Thread("小兔子") {
public void run() {
int count = 0;
while(count<100) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
count+=10;
if (count%10==0) {
System.out.println("小兔子跑了"+count+"米");
}
//到70米停两秒
if (count==70) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
t1.start();
t2.start();
}
输出结果:每次不同