Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In multithreading: How to determine which thread stops first

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.!

like image 474
Ankit Shukla Avatar asked Aug 01 '10 10:08

Ankit Shukla


2 Answers

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!");
    }
}
like image 194
cHao Avatar answered Nov 14 '22 21:11

cHao


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.

like image 28
sje397 Avatar answered Nov 14 '22 21:11

sje397