added ex S1

This commit is contained in:
Louis Heredero 2025-01-06 16:05:48 +01:00
parent a7216b1642
commit dbd83223fe
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
3 changed files with 77 additions and 0 deletions

View File

@ -0,0 +1,33 @@
package exercises.ex_s1;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
public class Cow implements Runnable {
private String name;
private ConcurrentHashMap<String, Integer> stalls;
private final Random random = new Random();
public Cow(String name, ConcurrentHashMap<String, Integer> stalls) {
this.name = name;
this.stalls = stalls;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep((long) (1000L + Math.random() * 5000L));
} catch (InterruptedException e) {
break;
}
String key = "box" + random.nextInt(1, 4);
Integer units = stalls.replace(key, 0);
if (units == null || units == 0) {
System.out.println(name + " ate nothing");
} else {
System.out.println(name + " ate " + units + " units of food from " + key);
}
}
}
}

View File

@ -0,0 +1,30 @@
package exercises.ex_s1;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
public class Farmer implements Runnable {
private String name;
private ConcurrentHashMap<String, Integer> stalls;
private final Random random = new Random();
public Farmer(String name, ConcurrentHashMap<String, Integer> stalls) {
this.name = name;
this.stalls = stalls;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep((long) (1000L + Math.random() * 2000L));
} catch (InterruptedException e) {
break;
}
String key = "box" + random.nextInt(1, 4);
int units = random.nextInt(10, 100);
stalls.put(key, units);
System.out.println(name + " puts " + units + " units of food in " + key);
}
}
}

View File

@ -0,0 +1,14 @@
package exercises.ex_s1;
import java.util.concurrent.ConcurrentHashMap;
public class TestingConcurrentHashMap_Farm {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> animalStallMap = new ConcurrentHashMap<>();
new Thread(new Farmer("Verena", animalStallMap)).start();
new Thread(new Farmer("Pierre", animalStallMap)).start();
for (int i = 1; i < 10; i++) {
new Thread(new Cow("Cow" + i, animalStallMap)).start();
}
}
}