import java.util.Random; import java.util.ArrayList; import java.util.concurrent.locks.*; class Bord { Lock lc = new ReentrantLock(); ArrayList bordet = new ArrayList<>(); int antBarista; Condition ikkeTom = lc.newCondition(); Bord(int antBarista) { this.antBarista = antBarista; } void server(String kaffe) { lc.lock(); try { bordet.add(kaffe); ikkeTom.signalAll(); } finally { lc.unlock(); } } String hentKaffe() { lc.lock(); try { while(bordet.size() == 0 && antBarista != 0) { ikkeTom.await(); } if(bordet.size() != 0) { return bordet.remove(0); } } catch(InterruptedException e) { System.exit(1); } finally { lc.unlock(); } return null; } void ferdig() { lc.lock(); try { antBarista--; ikkeTom.signalAll(); } finally { lc.unlock(); } } } class Kaffedrikker implements Runnable { Bord bord; String id; Kaffedrikker(Bord bord, String id) { this.bord = bord; this.id = id; } public void run() { int ant = 0; String drikke = bord.hentKaffe(); while(drikke != null) { System.out.println(id + " har drukket " + drikke); ant++; drikke = bord.hentKaffe(); } System.out.println(id + " har totalt drukket " + ant + " kopper"); } } class Barista implements Runnable { private final String[] drikker = {"Americano", "Caf¨¦ au lait", "Caff¨¨ latte", "Caff¨¨ mocca", "Espresso", "Cortado"}; Bord bord; String id; Barista(Bord bord, String id) { this.bord = bord; this.id = id; } public void run() { for(int i = 0; i < 10; i++) { String drikke = drikker[new Random().nextInt(drikker.length)]; System.out.println(id + " har laget " + drikke); bord.server(drikke); } bord.ferdig(); } } class Hoved { public static void main(String[] args) { int antBarista = 2; int antDrikker = 10; Bord bord = new Bord(2); for(int i = 0; i < antBarista; i++) { new Thread(new Barista(bord, i+"")).start(); } for(int i = 0; i < antDrikker; i++) { new Thread(new Kaffedrikker(bord, i+"")).start(); } } }