You are on page 1of 3

Experiment No.2.

Write a Java multi-threaded program to implement the tortoise and hare story. Make the hare sleep at the mid of the
way and let the tortoise win.

Source Code:

public class thread_demo 

   public static void main(String[] args)

   {

   Thread tortoise = new Tortoise();    //Creating an object of the tortoise thread 

   tortoise.start();             //Starting the first thread

   for(int a=1;a<11;a++)

      {

       System.out.println("Distance covered by HARE   = "+(a));  

      }

  System.out.println("!!!!!!!!!!!!!!!HARE IS GOING TO SLEEP!!!!!!!!!!!!!!!!!!!!!");  //hare going to sleep

  try

  {

   Thread.sleep(3000);              // current thread is hare

  }

  catch(InterruptedException ie)

  {

  

  }

  System.out.println("!!!!!!!!!!!!!!HARE AGAIN STARTED THE RACE !!!!!!!!!!!!!!!!");      //hare wakes up

  for(int b=11;b<21;b++)

   System.out.println("Distance covered by HARE   = "+(b));

  System.out.println("!!!!!!!!!!!!!!!!!!!!HARE HAS COMPLETED THE RACE !!!!!!!!!!!!!!!!!!!");


 }

class Tortoise extends Thread

{  

  public void run()

  {

        for(int c=1;c<21;c++)

        {

         System.out.println("Distance covered by TORTOISE = "+c);   

        }

        System.out.println("!!!!!!!!!!!!!!!!TORTOISE HAS WON THE RACE !!!!!!!!!!!!!!!!!!!!!");   // tortoise won the race

 }

Output:

Text Books

T1: Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill publishing company Ltd.

T2: Object Oriented Programming Using Java – IBM Study Material.

Reference Books

R1: Programming with Java by Balaguruswamy, – A primer, Tata McGraw Hill.

R2 : Understanding Object-Oriented Programming with JAVA by Timothy Budd

Research Papers

1.https://www.researchgate.net/publication/337482569_Threads_and_Multithreaded_in_java
2.https://www.researchgate.net/publication/
330278781_Analysis_of_Multithreading_in_Java_for_Symbolic_Computation_on_Multicore_Processors

3.https://www.academia.edu/Documents/in/Multi-threading

You might also like