From fe3d1aac3588bb8f6766e4395a9981071a09c60d Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 7 Jan 2025 15:40:44 +0100 Subject: [PATCH] added ex Y --- src/exercises/ex_y/RaceTester.java | 21 +++++++++++++++ src/exercises/ex_y/Runner.java | 43 ++++++++++++++++++++++++++++++ src/exercises/ex_y/answers.txt | 1 + 3 files changed, 65 insertions(+) create mode 100644 src/exercises/ex_y/RaceTester.java create mode 100644 src/exercises/ex_y/Runner.java create mode 100644 src/exercises/ex_y/answers.txt diff --git a/src/exercises/ex_y/RaceTester.java b/src/exercises/ex_y/RaceTester.java new file mode 100644 index 0000000..e9b5a58 --- /dev/null +++ b/src/exercises/ex_y/RaceTester.java @@ -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(); + } +} diff --git a/src/exercises/ex_y/Runner.java b/src/exercises/ex_y/Runner.java new file mode 100644 index 0000000..9782cf7 --- /dev/null +++ b/src/exercises/ex_y/Runner.java @@ -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; + } +} diff --git a/src/exercises/ex_y/answers.txt b/src/exercises/ex_y/answers.txt new file mode 100644 index 0000000..a47ac6d --- /dev/null +++ b/src/exercises/ex_y/answers.txt @@ -0,0 +1 @@ +We should use a Phaser as it allows for threads to wait on each other before moving to the next step