From 1cfc40afeddb12c3dc5a2ee951b817474d7136f0 Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 7 Jan 2025 14:19:04 +0100 Subject: [PATCH] added ex U --- src/exercises/ex_u/FamilyMember.java | 22 ++++++++++++++++++ .../TestingCountDownLatch_FamilyTrip.java | 23 +++++++++++++++++++ src/exercises/ex_u/Vehicle.java | 14 +++++++++++ 3 files changed, 59 insertions(+) create mode 100644 src/exercises/ex_u/FamilyMember.java create mode 100644 src/exercises/ex_u/TestingCountDownLatch_FamilyTrip.java create mode 100644 src/exercises/ex_u/Vehicle.java diff --git a/src/exercises/ex_u/FamilyMember.java b/src/exercises/ex_u/FamilyMember.java new file mode 100644 index 0000000..135aa4b --- /dev/null +++ b/src/exercises/ex_u/FamilyMember.java @@ -0,0 +1,22 @@ +package exercises.ex_u; + +import java.util.concurrent.CountDownLatch; + +public class FamilyMember implements Runnable { + private final String name; + private final Vehicle vehicle; + private final CountDownLatch countDownLatch; + + public FamilyMember(String name, Vehicle vehicle, CountDownLatch countDownLatch) { + this.name = name; + this.vehicle = vehicle; + this.countDownLatch = countDownLatch; + } + + @Override + public void run() { + vehicle.addSuitcase(name + "'s suitcase"); + System.out.println(name + " has loaded their suitcase"); + countDownLatch.countDown(); + } +} diff --git a/src/exercises/ex_u/TestingCountDownLatch_FamilyTrip.java b/src/exercises/ex_u/TestingCountDownLatch_FamilyTrip.java new file mode 100644 index 0000000..3c8c7df --- /dev/null +++ b/src/exercises/ex_u/TestingCountDownLatch_FamilyTrip.java @@ -0,0 +1,23 @@ +package exercises.ex_u; + +import java.util.concurrent.CountDownLatch; + +public class TestingCountDownLatch_FamilyTrip { + public static void main(String[] args) throws InterruptedException { + Vehicle seatAlhambra = new Vehicle(); + seatAlhambra.printVehicleContent(); + String[] family = {"Jean", "Anna", "Joseph", "Martha", "Eleonore", "Paul", "Catarina"}; + // Create a countDownLatch + CountDownLatch countDownLatch = new CountDownLatch(family.length); + + // Start the family members + // and synchronize them before the start + for (int i = 0; i < family.length; i++) { + new Thread(new FamilyMember(family[i], seatAlhambra, countDownLatch)).start(); + } + countDownLatch.await(); + + seatAlhambra.printVehicleContent(); + System.out.println("Family trip can start"); + } +} \ No newline at end of file diff --git a/src/exercises/ex_u/Vehicle.java b/src/exercises/ex_u/Vehicle.java new file mode 100644 index 0000000..9108372 --- /dev/null +++ b/src/exercises/ex_u/Vehicle.java @@ -0,0 +1,14 @@ +package exercises.ex_u; + +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; + +public class Vehicle { + private Queue suitcases = new ConcurrentLinkedQueue<>(); + public void addSuitcase(String suitcase) { + suitcases.add(suitcase); + } + public void printVehicleContent() { + System.out.println("Suitcases: " + suitcases); + } +}