import java.util.ArrayList; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.Condition; class ConditionsMain { public static void main(String[] args) { VaksineMonitor monitor = new VaksineMonitor(); Runnable vaksineProd = new Vaksineprodusent(monitor); Runnable sykepleier = new Sykepleier(monitor); Thread tVaksineProd = new Thread(vaksineProd); Thread tSykepleier = new Thread(sykepleier); tVaksineProd.start(); tSykepleier.start(); } } class Vaksineprodusent implements Runnable { VaksineMonitor monitor; Vaksineprodusent(VaksineMonitor vm) { monitor = vm; } @Override public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(4000); monitor.leggInnVaksine("Vaksine"); } catch (InterruptedException e) { System.out.println(e); } } } } class Sykepleier implements Runnable { VaksineMonitor monitor; Sykepleier(VaksineMonitor vm) { monitor = vm; } @Override public void run() { for (int i = 0; i < 10; i++) { String vaksine = monitor.taUtVaksine(); try { Thread.sleep(1000); System.out.println("Satt 1 vaksine dose. "); Thread.sleep(1000); System.out.println("Satt 1 vaksine dose. "); Thread.sleep(1000); System.out.println("Satt 1 vaksine dose. "); } catch (InterruptedException e) { System.out.println(e); } } } } class VaksineMonitor { private ArrayList vaksiner = new ArrayList<>(); private ReentrantLock lock = new ReentrantLock(); private Condition ikkeTom = lock.newCondition(); public String taUtVaksine() { lock.lock(); try { while (vaksiner.isEmpty()) { ikkeTom.await(); } return vaksiner.remove(0); } catch (InterruptedException e) { System.out.println(e); } finally { lock.unlock(); } return "Fikk ikke hentet vaksine"; } public void leggInnVaksine(String v) { lock.lock(); try { Thread.sleep(3000); vaksiner.add(v); ikkeTom.signalAll(); } catch (InterruptedException e) { System.out.println(e); } finally { lock.unlock(); } } }