package run;
public class Race {
public static void main(String[] args) {
Race race = new Race();
//tortoiseRice tortoise =new Race().new tortoiseRice();
tortoiseRice tortoise = race.new tortoiseRice();
robbitRice robbit = race.new robbitRice();
Thread t = new Thread(tortoise);
Thread r = new Thread(robbit);
t.start();
r.start();
while(ready <2){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (Race.lock) {
lock.notifyAll();
}
}
int Distance = 10000;
static int ready;
private static Object lock = new Object();
//tortoise
class tortoiseRice implements Runnable{
@Override
public void run() {
synchronized (lock) {
ready++;
try {
Race.lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int tortoiseDistance = 0;
for(int i=0;tortoiseDistance<Distance;i++){
tortoiseDistance++;
System.out.println("乌龟跑了"+tortoiseDistance+"米");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("乌龟跑完了比赛!");
}
}
//robbit
class robbitRice implements Runnable{
@Override
public void run() {
synchronized (lock) {
ready++;
try {
Race.lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int robbitDistance = 0;
for(int i=0;robbitDistance<=Distance;i++){
robbitDistance += 5;
System.out.println("兔子跑了"+robbitDistance+"米");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("兔子跑完了比赛!");
}
}
}