package com.hy.Test;
public class TortoiseRabbit {
public static void main(String[] args) {
int distance = 100;
TRRunnable rabbit = new TRRunnable("兔子",8,distance);
TRRunnable tortoise = new TRRunnable("乌龟",4,distance);
Thread trabbit = new Thread(rabbit);
Thread ttortoise = new Thread(tortoise);
trabbit.start();
ttortoise.start();
}
}
class TRRunnable implements Runnable{
private String name;
private int speed;
private int distance;
public TRRunnable(){
}
public TRRunnable(String name,int speed,int distance){
this.name=name;
this.speed=speed;
this.distance=distance;
}
@Override
public void run(){
int lucheng=0;
while(lucheng<distance){
lucheng+=speed;
try {
System.out.println(name+"路程:"+lucheng);
Thread.sleep(10);
if(lucheng==(distance*0.8)&&name.equals("兔子")){
System.out.println(name+":我先睡会儿");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name+":我到终点了");
}
}
兔子路程:8
乌龟路程:4
兔子路程:16
乌龟路程:8
乌龟路程:12
兔子路程:24
兔子路程:32
乌龟路程:16
乌龟路程:20
兔子路程:40
兔子路程:48
乌龟路程:24
兔子路程:56
乌龟路程:28
乌龟路程:32
兔子路程:64
兔子路程:72
乌龟路程:36
兔子路程:80
乌龟路程:40
乌龟路程:44
兔子:我先睡会儿
乌龟路程:48
乌龟路程:52
乌龟路程:56
乌龟路程:60
乌龟路程:64
乌龟路程:68
乌龟路程:72
乌龟路程:76
乌龟路程:80
乌龟路程:84
乌龟路程:88
乌龟路程:92
乌龟路程:96
乌龟路程:100
乌龟:我到终点了
兔子路程:88
兔子路程:96
兔子路程:104
兔子:我到终点了
|
|