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- // Refaktorert versjon class Bil implements Runnable { private Veistump enVei, toVei; private int ind; public Bil(Veistump en, Veistump to, int i) { enVei = en; toVei = to; ind = i; } public void run() { 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("FEIL1"); 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("FEIL2"); 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("FEIL3"); System.exit(1); } finally { l?s.unlock(); } } public void friVei() { l?s.lock(); try { veiLedig = true; ledig.signalAll(); } finally { l?s.unlock(); } } } class SmaltVeistykkeV2 { 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 "); for (int ind = 1; ind <= 20; ind++) { try { Thread.sleep((int) (ran.nextFloat() * 1000)); } catch (InterruptedException e) { System.out.println("FEIL4"); System.exit(1); } Bil bilen1 = new Bil(venstre, hoyre, ind * 2 - 1); new Thread(bilen1).start(); try { Thread.sleep((int) (ran.nextFloat() * 1000)); } catch (InterruptedException e) { System.out.println("FEIL5"); System.exit(1); } Bil bilen2 = new Bil(hoyre, venstre, ind * 2); new Thread(bilen2).start(); } System.out.println(" 40 biler er startet "); System.out.println(" Main er ferdig "); } }