diff --git a/src/exercises/ex_s1/Cow.java b/src/exercises/ex_s1/Cow.java new file mode 100644 index 0000000..8581b94 --- /dev/null +++ b/src/exercises/ex_s1/Cow.java @@ -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 stalls; + private final Random random = new Random(); + + public Cow(String name, ConcurrentHashMap 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); + } + } + } +} diff --git a/src/exercises/ex_s1/Farmer.java b/src/exercises/ex_s1/Farmer.java new file mode 100644 index 0000000..ed1d84d --- /dev/null +++ b/src/exercises/ex_s1/Farmer.java @@ -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 stalls; + private final Random random = new Random(); + + public Farmer(String name, ConcurrentHashMap 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); + } + } +} diff --git a/src/exercises/ex_s1/TestingConcurrentHashMap_Farm.java b/src/exercises/ex_s1/TestingConcurrentHashMap_Farm.java new file mode 100644 index 0000000..a39faf1 --- /dev/null +++ b/src/exercises/ex_s1/TestingConcurrentHashMap_Farm.java @@ -0,0 +1,14 @@ +package exercises.ex_s1; + +import java.util.concurrent.ConcurrentHashMap; + +public class TestingConcurrentHashMap_Farm { + public static void main(String[] args) { + ConcurrentHashMap 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(); + } + } +}