import java.util.concurrent.CountDownLatch; public class CountDownLatchEksempel { public static void main(String[] args) { int numThreads = 10; Thread[] traader = new Thread[numThreads]; CountDownLatch start = new CountDownLatch(1); CountDownLatch halvveis = new CountDownLatch(numThreads); for (int i = 0; i < 10; i++) { traader[i] = new Thread(new CountDownArbeider(i, start, halvveis)); traader[i].start(); } System.out.println("Starter tr?der..."); start.countDown(); System.out.println("Venter p? tr?der..."); try { halvveis.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Venter p? tr?der igjen..."); for (Thread t : traader) { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Alle tr?der er ferdige!"); } } class CountDownArbeider implements Runnable { int id; CountDownLatch startSignal, halvveisSignal; public CountDownArbeider(int id, CountDownLatch startSignal, CountDownLatch halvveisSignal) { this.id = id; this.startSignal = startSignal; this.halvveisSignal = halvveisSignal; } @Override public void run() { try { startSignal.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Tr?d %d gjennomf?rer f?rste del av arbeidet.%n", id); try { // Simulerer at tr?den bruker tid p? ? jobbe Thread.sleep((int) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } halvveisSignal.countDown(); try { halvveisSignal.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Tr?d %d gjennomf?rer andre del av arbeidet.%n", id); try { // Simulerer at tr?den bruker tid p? ? jobbe Thread.sleep((int) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Tr?d %d er ferdig!%n", id); } }