Skip to content

Instantly share code, notes, and snippets.

@abd3lraouf
Created November 30, 2016 22:25
Show Gist options
  • Save abd3lraouf/e1a6e8af910b0e7499c88978b22f4ce7 to your computer and use it in GitHub Desktop.
Save abd3lraouf/e1a6e8af910b0e7499c88978b22f4ce7 to your computer and use it in GitHub Desktop.
public class Race {
private static boolean raceFinished = false;
private static String winner;
public static void main(String[] args) throws InterruptedException {
Thread[] players = new Thread[10];
// Fill the array
for (int i = 0; i < players.length; i++) {
players[i] = makeNewPlayer(i);
players[i].setName("Player " + (i + 1));
System.out.println(players[i].getName() +" added");
}
System.out.println("\nBegin race\n");
long startTime = System.currentTimeMillis();
// Start each Thread
for (Thread player : players) {
player.start();
System.out.println(player.getName() +" started");
}
// makes the main thread wait for the player
for (Thread player : players) {
player.join();
}
// Duration.between(startTime, Instant.now()) -> calculates the duration of race
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("\nThe race is finished. Duration : " + duration +" ms");
System.out.println("The winner is : " + winner);
}
private static Thread makeNewPlayer(int index) {
// Returns a new thread which it's run method loops for 100 time units
// (100 m)
return new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 100; j++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Now let the thread finish the race
// This method is called for each thread
finishRace(Thread.currentThread().getName());
}
});
}
// This method must be synchronized
private static synchronized void finishRace(String name) {
// Change a simple flag condition to prevent others from accessing it after
// it has been accessed the first time
// The first thread will make raceFinished true and others threads when they
// call this method won't be able to declare themselves as winners :D
if (!raceFinished) {
raceFinished = true;
winner = name;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment