added ex Y

This commit is contained in:
Louis Heredero 2025-01-07 15:40:44 +01:00
parent e959cdd466
commit fe3d1aac35
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
3 changed files with 65 additions and 0 deletions

View 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();
}
}

View 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;
}
}

View 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