import java.util.*; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; // Program som viser at vranglas (deadlock) kan oppst?. // Skrevet av Stein Gjessing 2017 - 2025, Magnus Skjegstad 2026- // Versjon 1, f?r programmet ble refaktorert class Bil implements Runnable { private Veistump enVei, toVei; Random ran; int indStart; public Bil(Veistump en, Veistump to, Random ran, int indStart) { enVei = en; toVei = to; this.ran = ran; this.indStart = indStart; } public void run() { for (int ind = indStart; ind <= 40; ind += 2) { try { Thread.sleep((int) (ran.nextFloat() * 1000)); } catch (InterruptedException e) { System.out.println("FEIL1"); System.exit(1); } System.out.println(" Bil nr " + ind + " venter p? ? passere " + enVei.del + " veistykke"); enVei.taVei(); // Det tar litt tid ? kj?re dette veistykket: try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println("FEIL2"); System.exit(1); } System.out.println(" Bil nr " + ind + " venter p? ? passere " + toVei.del + " veistykke"); toVei.taVei(); enVei.friVei(); // Det tar litt tid ? kj?re dette veistykket: try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println("FEIL3"); System.exit(1); } toVei.friVei(); System.out.println(" Bil nr " + ind + " har passert hele den smale veien "); System.out.println(); } } } class Veistump { private Lock l?s = new ReentrantLock(); private Condition ledig = l?s.newCondition(); private boolean veiLedig = true; final String del; public Veistump(String hvilken) { del = hvilken; } public void taVei() { l?s.lock(); try { while (!veiLedig) { ledig.await(); } // N? er veien ledig , den er min veiLedig = false; } catch (InterruptedException e) { System.out.println("FEIL4"); System.exit(1); } finally { l?s.unlock(); } } public void friVei() { l?s.lock(); try { veiLedig = true; ledig.signalAll(); } finally { l?s.unlock(); } } } class SmaltVeistykkeV1 { public static void main(String[] args) { Random ran = new Random(); System.out.println(); System.out.println(" Main starter "); Veistump venstre = new Veistump(" venstre "); Veistump hoyre = new Veistump(" h?yre "); Bil bilen1 = new Bil(venstre, hoyre, ran, 0); new Thread(bilen1).start(); Bil bilen2 = new Bil(hoyre, venstre, ran, 1); new Thread(bilen2).start(); System.out.println(" 40 biler er startet "); System.out.println(" Main er ferdig "); } }