Page 17
Practical 7:
Write a multithreaded program to implement the hare and tortoise racing
game. Make the hare sleep in the mid way and let the tortoise win.
Concept overview
Java.lang.runnable is an interface that is to be implemented by a class whose
instances are intended to be executed by a thread. There are two ways to start a new Thread
– Subclass Thread and implement runnable. There is no need of subclassing Thread when a
task can be done by overriding only run() method of runnable.
Multithreading i n Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
Class Diagram
Source Code
Class to implement runnable
public class implements Runnable{
Thread obj;
String Name;
mst( String name) {
Name = name;
System.out.println(Name+" is ready to race");
}
Page 18
public void run()
{
System.out.println(Name+" is running" );
try {
if(Name.equals(" rabbit "))
{
System.out.println(Name +" goes to sleep");
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + Name + " is interrupted.");
}
System.out.println(Name + " has completed the race.");
}
public void race () {
System.out.println(Name+"started the race" );
if (obj == null) {
obj = new Thread (this,Name);
obj.start();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
mst h = new mst(" rabbit ");
mst t = new mst(" Tortoise ");
h.race();
t.race();
}
}
OUTPUT:
Page 19
Assumptions and logic used
The assumption was that the rabbit/hare was to stop in the middle of the race. I used two threads as a
way to visualize the two participants. The thread was rabbit was kept on pause to show that he slept
during the race. And the thread of the tortoise was allowed to go on.
The concept of multithreading was used in order to implement this logic.