added ex U

This commit is contained in:
Louis Heredero 2025-01-07 14:19:04 +01:00
parent 28ab30e735
commit 1cfc40afed
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
3 changed files with 59 additions and 0 deletions

View File

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

View File

@ -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");
}
}

View File

@ -0,0 +1,14 @@
package exercises.ex_u;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class Vehicle {
private Queue<String> suitcases = new ConcurrentLinkedQueue<>();
public void addSuitcase(String suitcase) {
suitcases.add(suitcase);
}
public void printVehicleContent() {
System.out.println("Suitcases: " + suitcases);
}
}