import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.BrokenBarrierException; class Test { static final int NUM_THREADS = 5; public static void main(String[] args) { CountDownLatch cdl = new CountDownLatch(NUM_THREADS); CyclicBarrier cb = new CyclicBarrier(NUM_THREADS + 1); // Thread[] traader = new Thread[NUM_THREADS]; // for (int i = 0; i < NUM_THREADS; i++) { // traader[i] = new Thread(new Task()); // traader[i].start(); // } // try { // for (Thread traad : traader) { // traad.join(); // } // } catch (InterruptedException e) {} for (int i = 0; i < NUM_THREADS; i++) { new Thread(new Task(cdl, cb)).start(); } try { cb.await(); } catch (InterruptedException | BrokenBarrierException e) {} System.out.println("Alle traadene er ferdig"); } } class Task implements Runnable { static int idLager = 0; int id; Random r = new Random(); CountDownLatch cdl; CyclicBarrier cb; public Task(CountDownLatch cdl, CyclicBarrier cb) { this.cdl = cdl; this.cb = cb; id = idLager++; } public void run() { System.out.println("Starter traad nr " + id); try { Thread.sleep(r.nextInt(5000)); } catch (InterruptedException e) { System.out.println("Ble avbrutt"); } System.out.printf("Traad nr %d er ferdig\n", id); // cdl.countDown(); try { cb.await(); } catch (InterruptedException | BrokenBarrierException e) {} System.out.println("yaaay"); } }