import java.util.concurrent.*; public class CyclicBarrierEksempel { int tall, numThreads; Thread[] traader; CyclicBarrier bom; public CyclicBarrierEksempel(int numThreads) { this.numThreads = numThreads; bom = new CyclicBarrier(numThreads + 1); traader = new Thread[numThreads]; for (int i = 0; i < 10; i++) { traader[i] = new Thread(new CyclicArbeider(i, bom, this)); traader[i].start(); } } public void settIgang() { tall = 10; for (int i = 9; i >= -1; i--) { try { bom.await(); bom.await(); } catch (Exception e) { e.printStackTrace(); } tall = i; } tall = -1; try { bom.await(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Alle tr?der er ferdige."); } public int hentTall() { return tall; } public static void main(String[] args) { CyclicBarrierEksempel c = new CyclicBarrierEksempel(10); c.settIgang(); } } class CyclicArbeider implements Runnable { int id; CyclicBarrier bom; CyclicBarrierEksempel cbe; public CyclicArbeider(int id, CyclicBarrier bom, CyclicBarrierEksempel cbe) { this.id = id; this.bom = bom; this.cbe = cbe; } @Override public void run() { int tall = 10; try { bom.await(); } catch (Exception e) { e.printStackTrace(); } while (tall != -1) { int resultat = tall * id; System.out.printf("%d ganger %d er lik %d.%n", tall, id, resultat); try { bom.await(); bom.await(); } catch (Exception e) { e.printStackTrace(); } tall = cbe.hentTall(); } } }