added ex Y
This commit is contained in:
parent
e959cdd466
commit
fe3d1aac35
21
src/exercises/ex_y/RaceTester.java
Normal file
21
src/exercises/ex_y/RaceTester.java
Normal file
@ -0,0 +1,21 @@
|
||||
package exercises.ex_y;
|
||||
|
||||
import java.util.concurrent.Phaser;
|
||||
|
||||
public class RaceTester {
|
||||
public static final int NUM_RUNNERS = 10;
|
||||
public static final int NUM_STAGES = 5;
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
Phaser phaser = new Phaser();
|
||||
phaser.register();
|
||||
for (int i = 0; i < NUM_RUNNERS; i++) {
|
||||
new Thread(new Runner(NUM_STAGES, phaser)).start();
|
||||
}
|
||||
for (int i = 0; i <= NUM_STAGES; i++) {
|
||||
phaser.arriveAndAwaitAdvance();
|
||||
}
|
||||
System.out.println("Finished race");
|
||||
phaser.arriveAndDeregister();
|
||||
}
|
||||
}
|
43
src/exercises/ex_y/Runner.java
Normal file
43
src/exercises/ex_y/Runner.java
Normal file
@ -0,0 +1,43 @@
|
||||
package exercises.ex_y;
|
||||
|
||||
import exercises.Utils;
|
||||
|
||||
import java.util.concurrent.Phaser;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class Runner implements Runnable {
|
||||
private static AtomicInteger nextId = new AtomicInteger(0);
|
||||
private final int id;
|
||||
private final int maxStep;
|
||||
private final Phaser phaser;
|
||||
|
||||
public Runner(int maxStep, Phaser phaser) {
|
||||
id = nextId.getAndIncrement();
|
||||
this.maxStep = maxStep;
|
||||
this.phaser = phaser;
|
||||
phaser.register();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println(this + " is on the starting line");
|
||||
phaser.arriveAndAwaitAdvance();
|
||||
|
||||
while (phaser.getPhase() <= this.maxStep) {
|
||||
System.out.println(this + " started stage " + phaser.getPhase());
|
||||
try {
|
||||
Utils.randomSleep(1000, 5000);
|
||||
} catch (InterruptedException e) {
|
||||
break;
|
||||
}
|
||||
System.out.println(this + " finished stage " + phaser.getPhase());
|
||||
phaser.arriveAndAwaitAdvance();
|
||||
}
|
||||
phaser.arriveAndDeregister();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Runner " + id;
|
||||
}
|
||||
}
|
1
src/exercises/ex_y/answers.txt
Normal file
1
src/exercises/ex_y/answers.txt
Normal file
@ -0,0 +1 @@
|
||||
We should use a Phaser as it allows for threads to wait on each other before moving to the next step
|
Loading…
Reference in New Issue
Block a user