import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.CountDownLatch; import java.util.Random; public class FinnHoyeste { private static final int ANT_TRAADER = 200; public static void main(String[] args) { CountDownLatch ferdig = new CountDownLatch(ANT_TRAADER); Tallmonitor monitor = new Tallmonitor(); for (int i = 0; i < ANT_TRAADER; i ++){ new Thread(new Tallgenerator(ferdig, monitor)).start(); } // Barriere try { ferdig.await(); } catch (InterruptedException ie) {} int hoyest = monitor.hentHoyeste(); System.out.println("Det h?yeste tallet var: " + hoyest + "."); } } class Tallgenerator implements Runnable { private static int IDgenerator = 0; private int minID; private CountDownLatch ferdigSignal; private Tallmonitor minMonitor; private Random random = new Random(); public Tallgenerator(CountDownLatch ferdig, Tallmonitor minMonitor) { minID = ++ IDgenerator; ferdigSignal = ferdig; this.minMonitor = minMonitor; } public void run() { // Tr?dens kode int generertTall = random.nextInt(250) * random.nextInt(250); minMonitor.settInnTall(generertTall); ferdigSignal.countDown(); } } class Tallmonitor { private int hoyesteHittil = 0; private Lock lock = new ReentrantLock(); public int hentHoyeste() { return hoyesteHittil; } public void settInnTall(int tall) { lock.lock(); try { //System.out.println("Tallet er: " + tall); if (tall > hoyesteHittil) { hoyesteHittil = tall; } } finally { lock.unlock(); } } }