import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class Valgsystem { public static void main(String[] args) { int antVelgere = 200; int antTellere = 200; CountDownLatch barriere = new CountDownLatch(antTellere); Valgbod boden = new Valgbod(); for (int i = 0; i < antVelgere; i++) { new Thread(new Velger(boden, barriere)).start(); } for (int i = 0; i < antTellere; i++) { new Thread(new Teller(boden, barriere)).start(); } try { barriere.await(); } catch (Exception e) {return;} boden.visStemmer(); } } // Monitor class Valgbod { Lock bodLaas = new ReentrantLock(); //Lock telleLaas = new ReentrantLock(); Condition nyStemme = bodLaas.newCondition(); //Condition teltStemme = bodLaas.newCondition(); List partier = new ArrayList(); List stemmer = new ArrayList(); HashMap talteStemmer = new HashMap<>(); Valgbod() { partier.add("V"); partier.add("M"); partier.add("H"); } void stem() { bodLaas.lock(); try { String parti = partier.get(new Random().nextInt(partier.size())); stemmer.add(parti); nyStemme.signal(); } finally { bodLaas.unlock(); } } void tellStemme() { bodLaas.lock(); try { while (stemmer.size() == 0) { nyStemme.await(); } String stemme = stemmer.remove(0); if (talteStemmer.containsKey(stemme)) { talteStemmer.replace(stemme, talteStemmer.get(stemme) + 1); } else {talteStemmer.put(stemme,1);} } catch (InterruptedException e) {return;} finally { bodLaas.unlock(); } } void visStemmer() { for (String k : talteStemmer.keySet()) { System.out.println(k + " : " + talteStemmer.get(k)); } } } class Velger implements Runnable { private Valgbod bod; private CountDownLatch latch; Velger(Valgbod b, CountDownLatch latch) { this.bod = b; this.latch = latch; } public void run() { try { int tid = new Random().nextInt(5); //Thread.sleep(tid*1000); bod.stem(); System.out.println(Thread.currentThread().getName() + " hra stemt! Det tok " + tid + " sekunder"); } catch (Exception e) {return;} } } class Teller implements Runnable { private Valgbod boden; private CountDownLatch latch; Teller(Valgbod b, CountDownLatch latch) { this.boden = b; this.latch = latch; } public void run() { try { boden.tellStemme(); latch.countDown(); } catch (Exception e) {return;} } }