import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.Condition; class MinRun implements Runnable { Monitor monitor; public MinRun(Monitor monitor) { this.monitor = monitor; } static int sum = 0; @Override public void run() { int teller = 0; while (teller < 35) { teller++; monitor.increment(); System.out.println(monitor.getSum()); } System.out.println("Sum: " + monitor.getSum()); } } class MinKunde implements Runnable { Monitor monitor; public MinKunde(Monitor monitor) { this.monitor = monitor; } @Override public void run() { int teller = 0; while (teller < 10) { teller++; monitor.decrement(); System.out.println(monitor.getSum()); } System.out.println("Sum: " + monitor.getSum()); } } class Monitor { Lock laas = new ReentrantLock(); Condition ventPaaArbeider = laas.newCondition(); private int sum = 0; public void increment() { laas.lock(); try { sum++; ventPaaArbeider.signal(); } finally { laas.unlock(); } } public void decrement() { laas.lock(); try { if (sum <= 0) { ventPaaArbeider.await(); } sum--; } catch (InterruptedException e) { System.out.println(e); } finally { laas.unlock(); } } public int getSum() { return sum; } } class Hovedprogram { public static void main(String[] args) { Monitor monitor = new Monitor(); // inneholder sum MinRun RunnableObjekt = new MinRun(monitor); MinRun RunnableObjekt2 = new MinRun(monitor); MinKunde kunde1 = new MinKunde(monitor); // RunnableObjekt.run(); // RunnableObjekt.run(); Thread traad3 = new Thread(kunde1); Thread traad4 = new Thread(kunde1); Thread traad5 = new Thread(kunde1); Thread traad6 = new Thread(kunde1); Thread traad7 = new Thread(kunde1); Thread traad = new Thread(RunnableObjekt); Thread traad2 = new Thread(RunnableObjekt2); traad3.start(); traad.start(); traad2.start(); traad4.start(); traad5.start(); traad6.start(); traad7.start(); } } //en tr?d skaper en egen programflyt i programmet (derav ordet tr?d) // et runnable-objekt definerer en oppgave som en tr?d kan kj?re //en monitor inneholder lagret data p? tvers av tr?der (alts? p? tvers av runnable-objekter) //monitor har ansvar for ? l?se metodene sine, og for ? sette await()-tilstander. //i et stort system, vi har arbeidertr?der, kundetr?der og en eller flere monitorer