added ex Y

This commit is contained in:
2025-01-07 15:40:44 +01:00
parent e959cdd466
commit fe3d1aac35
3 changed files with 65 additions and 0 deletions

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