import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; public class Barrier { static boolean running = true; static class Task2 implements Runnable { CyclicBarrier cbStart; CyclicBarrier cbdone; CountDownLatch cdl; Task2(CyclicBarrier cb, CyclicBarrier cb2, CountDownLatch cdl) { this.cdl = cdl; this.cbStart = cb; this.cbdone = cb2; } @Override public void run() { while (running) { try { cbStart.await(); int var = 0; for (int i = 0; i < 250; i++) { var++; Thread.sleep(1); } cbdone.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } cdl.countDown(); } } public static void main(String[] args) throws InterruptedException, BrokenBarrierException { int threads = 10; CyclicBarrier cbStart = new CyclicBarrier(threads+1); CyclicBarrier cbdone = new CyclicBarrier(threads + 1); CountDownLatch cdl = new CountDownLatch(threads); Thread[] ths = new Thread[threads]; Task2 t = new Task2(cbStart, cbdone, cdl); for (int i = 0; i < threads; i++) { ths[i] = new Thread(t); ths[i].start(); } for (int i = 0; i < 10; i++) { cbStart.await(); System.out.println("Starter: "+(i+1)); if (i == 9) running = false; cbdone.await(); System.out.println("Ferdig: " + (i + 1)); } cdl.await(); // Denne gjør det samme som cdl // for (Thread thread : ths) { // thread.join(); // } System.out.println("Alle er ferdige"); } }