import java.util.concurrent.CountDownLatch; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.Random; /** * A given number of threads, contenders, generate a Random * number. The contender who submitts the largest value wins. * In order for a contender to know if they won, they must be * able to wait until all contenders are done. */ public class CountDownExample { private static final int NUM_THREADS = 10; public static void main(String[] args) { // Make a barrier, set to wait for NUM_THREADS calls to countDown(). //CountDownLatch allDoneBarrier = new CountDownLatch(_____________); CountDownLatch allDoneBarrier = new CountDownLatch(NUM_THREADS); // Make and start threads. No need to store threads for waiting, // we can use the barrier for this. KeepLargestMonitor monitor = new KeepLargestMonitor(); for (int i = 0; i < NUM_THREADS; i++) { // fyller inn -------------- Runnable r = new Contender(monitor, allDoneBarrier); Thread t = new Thread(r); t.start(); // fylt inn ---------- } // Wait for all contenders to submitt a number. try { // fyller inn -------------- allDoneBarrier.await(); // fylt inn ---------- } catch (InterruptedException e) {} // trenger BrokenBarrierException? System.out.println("Largest: " + monitor.getLargest()); } } /* Monitor to save largest received value. */ class KeepLargestMonitor { private final Lock lock = new ReentrantLock(); private int largest; public int getLargest() { return largest; } public void giveNumber(int number) { // Laas laasen: // fyller inn -------------- lock.lock(); // fylt inn ---------- try { largest = Math.max(largest, number); } finally { lock.unlock(); } } } /* Contender class may skip constructor if made anonymous. */ //class Contender implements ________________ { class Contender implements Runnable { private final KeepLargestMonitor monitor; private final CountDownLatch allDoneBarrier; private final int id; private static int numberOfWorkersDoingThisJob = 0; public Contender(KeepLargestMonitor monitor, CountDownLatch allDoneBarrier){ //this.id = ______________; this.id = numberOfWorkersDoingThisJob++; this.monitor = monitor; this.allDoneBarrier = allDoneBarrier; } //public void _____________() { public void run() { // Generate and submit a random number. Random random = new Random(); int number = random.nextInt(100); // Max of 100 System.out.printf("Thread #%d generated number: %d\n", id, number); monitor.giveNumber(number); // Report that we are done, then wait for the rest // signaliserer at traaden har gitt sitt tall til monitoren allDoneBarrier.countDown(); //allDoneBarrier.__________________(); try { // be traaden om aa vente til de andre er ferdig: //allDoneBarrier.______________(); allDoneBarrier.await(); } catch (InterruptedException e ) {} // If we submitted the largest value, we won! if (number == monitor.getLargest()) { System.out.printf("Thread #%d won!\n", id); } } }