I have a task to create a race in Java using Threads with 10 different participants who will run distance of 100 m and the winner is, of course, who gets first to the 100m.
However, the race should end when all participants finish the race and after the race program should also display the time that was needed for every participant to finish the race.
My question is how to add time in program, since I tried using 2D for loop, but didn't succeed.
This is my so far code
P.S My Syso should like smthing like:
Distance covered by Kazim was 100m and 40 seconds
Distance covered by Lloran was 100m and 36 seconds.
I haven't implemented time at all
public class Race implements Runnable
{
public static String winner;
public void race()
{
for (int distance = 1; distance <= 100; distance++)
{
System.out.println("Distance covered is by" + " "
+ Thread.currentThread().getName() + " is" + " " + distance);
boolean isRaceFinished = this.isRaceFinished(distance);
if (isRaceFinished)
{
break;
}
}
}
private boolean isRaceFinished(int distance)
{
boolean isRaceFinished = false;
if (winner == null && distance == 100)
{
String winnerName = Thread.currentThread().getName();
winner = winnerName;
System.out.println("The winner is" + " " + winner);
}
else if (winner == null)
{
isRaceFinished = false;
}
else if (winner != null)
{
isRaceFinished = true;
}
return isRaceFinished;
}
@Override
public void run()
{
this.race();
}
}
public class Main
{
public static void main(String[] args)
{
Race race = new Race();
Thread t1 = new Thread(race, "Dean");
Thread t2 = new Thread(race, "Lloran");
Thread t3 = new Thread(race, "Vinsel");
Thread t4 = new Thread(race, "Jimmy");
Thread t5 = new Thread(race, "Khan");
Thread t6 = new Thread(race, "Kazim");
Thread t7 = new Thread(race, "Richards");
Thread t8 = new Thread(race, "Malvo");
Thread t9 = new Thread(race, "Leddan");
Thread t10 = new Thread(race, "Joseph");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
t10.start();
}
}
t1). You should use something like aCountdownLatchto block the threads until all are ready.winner, otherwise it is not guaranteed that all threads will see that a winner has been set. Or use anAtomicReference<String>, of course.