龟兔赛跑:20米 //只要为了看到效果,所有距离缩短了
要求:
1.兔子每秒0.5米的速度,每跑2米休息10秒,
2.乌龟每秒跑0.1米,不休息
3.其中一个跑到终点后另一个不跑了!
import java.text.DecimalFormat;
/**
* @Author: 张
* @Date: 2019/2/11 16:41
* @Version: 1.0
* @Description: 1.0
*/
public class RabbitRaceTest {
public final static int DISTANCE = 20;
public static Double DISTANCE_RABBIT = new Double(DISTANCE);
public static Double DISTANCE_TORTOISE = new Double(DISTANCE);
public static final DecimalFormat df = new DecimalFormat("#.0");
private static volatile boolean isFinish = false;
public static class Rabbit implements Runnable{
@Override
public void run() {
while(true){
if(isFinish) {
break;
}
if(DISTANCE_RABBIT <= 0){
System.out.println("兔子:我赢了!");
isFinish = true;
break;
}
for(int i = 0;i<4;i++){
DISTANCE_RABBIT = findDouble(DISTANCE_RABBIT- 0.5);
System.out.println("兔子:我还剩余"+DISTANCE_RABBIT);
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
System.out.println("兔子:我要休息10秒");
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static Double findDouble(Double d){
String distanceStr = df.format(d);
return Double.valueOf(distanceStr);
}
public static class Tortoise implements Runnable{
@Override
public void run() {
while(true){
if(isFinish){
break;
}
if(DISTANCE_TORTOISE <= 0){
System.out.println("乌龟:我赢了!");
isFinish = true;
break;
}
DISTANCE_TORTOISE = findDouble(DISTANCE_TORTOISE - 0.1);
System.out.println("乌龟:我还剩余"+ DISTANCE_TORTOISE);
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args){
Thread rabbitThread = new Thread(new Rabbit());
Thread tortoiseThread = new Thread(new Tortoise());
System.out.println("开始@!!");
rabbitThread.start();
tortoiseThread.start();
}
}
例子来源于https://blog.csdn.net/wenzhi20102321/article/details/52524545