import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Saftbod { int antallLiterSaft = 0; Lock laas = new ReentrantLock(); Condition ikkeTom = laas.newCondition(); boolean ferdigProdusert = false; // Produsent-metode public void produserSaft(int liter) { laas.lock(); try { // logikken.... antallLiterSaft += liter; ikkeTom.signalAll(); } finally { laas.unlock(); } } // Konsument-metode public void kjoepSaft(int liter) { laas.lock(); try { while (!ferdigProdusert && antallLiterSaft < liter) { ikkeTom.await(); } if (ferdigProdusert) { System.out.println("Stengt. Var ikke nok saft.. Stikker hjem"); return; } antallLiterSaft -= liter; } catch (InterruptedException e) { System.exit(-1); } finally { laas.unlock(); } } public void erFerdigProdusert() { laas.lock(); try { // Formål: unngå at ventende kunder skal stå og vente ferdigProdusert = true; ikkeTom.signalAll(); } finally { laas.unlock(); } } }