Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a class definition that extends Thread for a racehorse. It will have a str

ID: 642262 • Letter: W

Question

Write a class definition that extends Thread for a racehorse. It will have a string data field for the name of the racehorse, a constructor to set the name, and the run() method. The racetrack will be from spot 1 to 100, the run() will use a loop to print their spot number (the loop variable that increments) and name 100 times before printing they are done at the end of the loop. If there are multiple threads, the 100 time for loops will be running for each racehorse at the same time.

Here is the code:

package threads14;
/*
* This class will define a racehorse
*/
public class racehorse141 extends Thread
{
    private String name;
   
    public racehorse141(String n)
    {
        name = n;
    }

    public void run() // override run() method from Thread, called by start()
    {
        int i;
        for (i = 1; i <= 100; i++)
            System.out.print(i + name + " ");
        System.out.println(name + " done");
    }
}

1b.    Write the main class that will declare 4 racehorses and set their priority based upon random numbers (from 1 - 10, then setPriority() for each racehorse object). Then start() all 4 racehorses and see which racehorse can get to 100 times through their for loops first and win the race. If there seems to not be enough switching back and forth between racehorse threads, you can change to loop more than 100 times.

Explanation / Answer

// racehorse141.java

public class racehorse141 extends Thread{
   private String name;

public racehorse141(String n){
name = n;
}

public void run(){
int i;
for (i = 1; i <= 100; i++)
System.out.print(i + name + " ");
System.out.println(name + " done");
}
}

// racehorse141Test.java

import java.util.Random;
public class racehorse141Test {
   public static void main(String args[]){
       racehorse141 horse1 = new racehorse141("Horse1");
       racehorse141 horse2 = new racehorse141("Horse2");
       racehorse141 horse3 = new racehorse141("Horse3");
       racehorse141 horse4 = new racehorse141("Horse4");
       Random r = new Random();
       horse1.setPriority(r.nextInt(10) + 1);
       horse2.setPriority(r.nextInt(10) + 1);
       horse3.setPriority(r.nextInt(10) + 1);
       horse4.setPriority(r.nextInt(10) + 1);
       horse1.start();
       horse2.start();
       horse3.start();
       horse4.start();
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote