added ex X
This commit is contained in:
parent
fe3d1aac35
commit
c7d054e973
35
src/exercises/ex_x/FamilyMember.java
Normal file
35
src/exercises/ex_x/FamilyMember.java
Normal 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");
|
||||
}
|
||||
}
|
24
src/exercises/ex_x/TestingPhaserFamilyBikeTrip.java
Normal file
24
src/exercises/ex_x/TestingPhaserFamilyBikeTrip.java
Normal 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.");
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user