added ex T

This commit is contained in:
Louis Heredero 2025-01-07 13:57:09 +01:00
parent c89a9b3a90
commit 28ab30e735
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
5 changed files with 104 additions and 0 deletions

7
src/exercises/Utils.java Normal file
View File

@ -0,0 +1,7 @@
package exercises;
public class Utils {
public static void randomSleep(long min, long max) throws InterruptedException {
Thread.sleep((long) (min + Math.random() * max));
}
}

View File

@ -0,0 +1,24 @@
package exercises.ex_t;
import java.util.concurrent.Semaphore;
public class BowlSemaphore {
private boolean isFull = false;
private Semaphore semaphore = new Semaphore(1);
public boolean fill() throws InterruptedException {
semaphore.acquire();
boolean wasFull = isFull;
isFull = true;
semaphore.release();
return wasFull;
}
public boolean empty() throws InterruptedException {
semaphore.acquire();
boolean wasFull = isFull;
isFull = false;
semaphore.release();
return wasFull;
}
}

View File

@ -0,0 +1,29 @@
package exercises.ex_t;
import exercises.Utils;
public class Dog implements Runnable {
private final String name;
private final BowlSemaphore[] bowls;
public Dog(String name, BowlSemaphore[] bowls) {
this.name = name;
this.bowls = bowls;
}
@Override
public void run() {
while (true) {
for (int i = 0; i < 3; i++) {
BowlSemaphore bowl = bowls[i];
try {
if (bowl.empty()) {
System.out.println(name + " ate from bowl " + i);
Utils.randomSleep(10000, 20000);
break;
}
} catch (InterruptedException _) {}
}
}
}
}

View File

@ -0,0 +1,28 @@
package exercises.ex_t;
import exercises.Utils;
public class Feeder implements Runnable {
private final String name;
private final BowlSemaphore[] bowls;
public Feeder(String name, BowlSemaphore[] bowls) {
this.name = name;
this.bowls = bowls;
}
@Override
public void run() {
while (true) {
for (int i = 0; i < 3; i++) {
BowlSemaphore bowl = bowls[i];
try {
if (!bowl.fill()) {
System.out.println(name + " filled bowl " + i);
Utils.randomSleep(1000, 3000);
}
} catch (InterruptedException _) {}
}
}
}
}

View File

@ -0,0 +1,16 @@
package exercises.ex_t;
public class TestingSemaphore_DogBreeder {
public static void main(String[] args) {
BowlSemaphore[] bowlsSemaphores = new BowlSemaphore[3];
for (int i = 0; i < 3; i++) {
bowlsSemaphores[i] = new BowlSemaphore();
}
new Thread(new Feeder("Marco", bowlsSemaphores)).start();
new Thread(new Feeder("Luisa", bowlsSemaphores)).start();
for (int i = 1; i < 10; i++) {
new Thread(new Dog("Dog" + i, bowlsSemaphores)).start();
}
}
}