Java code
/**
* A multithreaded program simulating the tortoise and hare races. <br>
* The rabbit is 5 times times faster than the tortoise, but the time of rest is 10 times times longer.
*
* @author Zhaoqing, Java Century Network (java2000.net)
*
*/
public class T {
public static void Main (string[] args) {
Tortoiserace a = new Tortoiserace ();
Thread runner1 = new Thread (a);
Rabbitrace B = new Rabbitrace ();
Thread runner2 = new Thread (b);
Runner1.start ();
Runner2.start ();
while (Ready < 2) {
try {
Thread.Sleep (1);
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
Synchronized (lock) {
Lock.notifyall ();
}
}
Static Object lock = new Object ();
static int ready = 0;
}
Class Tortoiserace implements Runnable {
public void Run () {
Synchronized (T.lock) {
t.ready++;
try {
T.lock.wait ();
catch (Interruptedexception E1) {
E1.printstacktrace ();
}
}
int tortoisedistance = 0;
for (int i = 0; Tortoisedistance <= 1000; i++) {
tortoisedistance++;
System.out.println ("Turtle ran 1 meters!");
try {
Thread.Sleep (1);
catch (Interruptedexception e) {
}
}
System.out.println ("The tortoise has already run the race journey!");
}
}
Class Rabbitrace implements Runnable {
public void Run () {
t.ready++;
Synchronized (T.lock) {
try {
T.lock.wait ();
catch (Interruptedexception E1) {
E1.printstacktrace ();
}
}
int rabbitdistance = 0;
for (int j = 0; Rabbitdistance <= 1000; J + +) {
Rabbitdistance + 5;
System.out.println ("Rabbit ran 5 meters!");
try {
Thread.Sleep (10);
catch (Interruptedexception e) {
}
}
System.out.println ("Rabbit runs the race!");
}
}