added ex X

This commit is contained in:
Louis Heredero 2025-01-07 15:47:58 +01:00
parent fe3d1aac35
commit c7d054e973
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
2 changed files with 59 additions and 0 deletions

View File

@ -0,0 +1,35 @@
package exercises.ex_x;
import exercises.Utils;
import java.util.concurrent.Phaser;
public class FamilyMember implements Runnable {
private final String name;
private final Phaser phaser;
private final int numSteps;
public FamilyMember(String name, Phaser phaser, int numSteps) {
this.name = name;
this.phaser = phaser;
this.numSteps = numSteps;
phaser.register();
}
@Override
public void run() {
int step = 0;
while (step < numSteps) {
step = phaser.getPhase() + 1;
try {
System.out.println(name + ": Step " + step + " started");
Utils.randomSleep(1000, 3000);
phaser.arriveAndAwaitAdvance();
} catch (InterruptedException e) {
break;
}
}
phaser.arriveAndDeregister();
System.out.println(name + " has arrived");
}
}

View File

@ -0,0 +1,24 @@
package exercises.ex_x;
import java.util.concurrent.Phaser;
public class TestingPhaserFamilyBikeTrip {
public static void main(String[] args) {
String[] family = {"Father", "Mother", "Son", "Daughter_1", "Daughter_2"};
String[] routes = {"Sierre", "Sion", "Martigny", "St-Maurice", "Aigle", "Vevey"};
Phaser phaser = new Phaser();
phaser.register();
System.out.println("The family leaves Brig for a bike trip to Vevey");
for (int i = 0; i < family.length; i++) {
new Thread(new FamilyMember(family[i], phaser, routes.length)).start();
}
for (int i = 0; i < routes.length; i++) {
phaser.arriveAndAwaitAdvance();
System.out.println("All family members arrived to " + routes[i]);
}
phaser.arriveAndDeregister();
System.out.println("End of the bike trip.");
}
}