Write a class named RaceHorse that extends Thread. Each RaceHorse has a name and run() method that displays the name 5000 times. Write a Java application that instantiates 2 RaceHorse objects. The last RaceHorse to finish is the loser.
This is the question. I have written the code for the two classes two run the thread Here are the codes:
RaceHorse
class RaceHorse extends Thread
{
public String name;
public RaceHorse(String name)
{
this.name = name;
}
public void run()
{
for(int i = 1 ; i <= 5000; i++)
{
System.out.println(i+" "+name);
}
System.out.println(name+" finished.");
}
}
Runner
class Runner{
public static void main(String args[])
{
RaceHorse obj = new RaceHorse("Lol");
RaceHorse obj2 = new RaceHorse("BOL");
Thread t = new Thread(obj);
Thread t2 = new Thread(obj2);
t.start();
t2.start();
}
}
Now my problem is I am unable to find which of the thread finishes first and which seconds, i.e. which of the horse wins and which loses.!
First off: your RaceHorse
objects are themselves threads. You should be able to say obj.start();
and it'd work just as well. So remove t
and t2
entirely.
Next, you'll need some way to notify the main thread about the winner.
public void run()
{
... your loop stuff ...
// this is how we're going to do the notification.
Runner.done();
}
public class Runner
{
private static RaceHorse winner = null;
synchronized static void done()
{
// Threads calling this are going to be RaceHorse objects.
// Now, if there isn't already a winner, this RaceHorse is the winner.
if (winner == null) winner = (RaceHorse) Thread.currentThread();
}
public static void main(String[] args)
{
... create the horses ...
// start the horses running
obj.start();
obj2.start();
// wait for them to finish
obj.join();
obj2.join();
System.out.println(winner.name + " wins!");
}
}
There's no doubt a better way, but one method might be to create a class (e.g. 'Trophy') that is thread safe, has a method 'getTrohpy' that only returns true on the first call, and pass a reference to an instance of Trophy to both threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With