A multithreaded code to simulate a turtle and rabbit race

Source: Internet
Author: User
Tags sleep

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!");

}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.