added ex V

This commit is contained in:
Louis Heredero 2025-01-07 14:44:35 +01:00
parent 1cfc40afed
commit e959cdd466
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
4 changed files with 104 additions and 0 deletions

View File

@ -0,0 +1,20 @@
package exercises.ex_v;
import java.util.Comparator;
import java.util.List;
public class Referee implements Runnable {
private final List<Result> results;
public Referee(List<Result> results) {
this.results = results;
}
@Override
public void run() {
System.out.println("Referee starts to establish ranking...");
results.sort(Result::compareTo);
System.out.println("PDG Team Ranking:");
results.forEach(System.out::println);
}
}

View File

@ -0,0 +1,28 @@
package exercises.ex_v;
public class Result implements Comparable<Result>{
private final int time;
private final String team;
public Result(String team, int time) {
this.time = time;
this.team = team;
}
public int getTime() {
return time;
}
public String getTeam() {
return team;
}
@Override
public int compareTo(Result result) {
return this.getTime() - result.getTime();
}
@Override
public String toString() {
return getTeam() + " : " + getTime() + "h";
}
}

View File

@ -0,0 +1,34 @@
package exercises.ex_v;
import exercises.Utils;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class Team implements Runnable {
private final String name;
private final List<Result> results;
private final CyclicBarrier barrier;
public Team(int i, List<Result> results, CyclicBarrier barrier) {
this.name = "Team " + i;
this.results = results;
this.barrier = barrier;
}
@Override
public void run() {
System.out.println(name + " : Started the race");
try {
Utils.randomSleep(1000, 5000);
} catch (InterruptedException _) {}
Result result = new Result(name, (int) (Math.random() * 20 + 1));
System.out.println(name + " : Finished the race in " + result.getTime() + " hours and is waiting for other teams");
results.add(result);
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException _) {}
}
}

View File

@ -0,0 +1,22 @@
package exercises.ex_v;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class TestingCyclicBarrier_PDG {
private static int NUM_TEAMS = 20;
public static void main(String[] args) {
List<Result> results = Collections.synchronizedList(new ArrayList<>());
System.out.println("Starting PDG with " + NUM_TEAMS + " teams ");
CyclicBarrier barrier = new CyclicBarrier(NUM_TEAMS, new Referee(results));
// Start the team threads and synchronize them.
// Make sure finally to order to order the results and print them
for (int i = 0; i < NUM_TEAMS; i++) {
new Thread(new Team(i, results, barrier)).start();
}
}
}