diff --git a/src/exercises/ex_x/FamilyMember.java b/src/exercises/ex_x/FamilyMember.java new file mode 100644 index 0000000..73ae6aa --- /dev/null +++ b/src/exercises/ex_x/FamilyMember.java @@ -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"); + } +} diff --git a/src/exercises/ex_x/TestingPhaserFamilyBikeTrip.java b/src/exercises/ex_x/TestingPhaserFamilyBikeTrip.java new file mode 100644 index 0000000..4e7179b --- /dev/null +++ b/src/exercises/ex_x/TestingPhaserFamilyBikeTrip.java @@ -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."); + } +}