Java Lab Practical 7
Java Lab Practical 7
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.
Class Diagram
Source Code
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