Java examples for Thread:CountDownLatch
Using CountDownLatch to manage threads
import java.util.concurrent.CountDownLatch; public class TestCountDownLatch { private static final int COUNT = 10; public static void main(String[] args) throws InterruptedException { CountDownLatch doneSignal = new CountDownLatch(COUNT); CountDownLatch startSignal = new CountDownLatch(1); for (int i = 1; i <= COUNT; i++) { new Thread(new Worker(i, doneSignal, startSignal)).start();//start }/* w w w. jav a2 s . c om*/ System.out.println("begin------------"); startSignal.countDown();//running try { doneSignal.await();//wait for other threads } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Ok"); } static class Worker implements Runnable { private final CountDownLatch doneSignal; private final CountDownLatch startSignal; private int beginIndex; public Worker(int beginIndex, CountDownLatch doneSignal, CountDownLatch startSignal) { this.startSignal = startSignal; this.beginIndex = beginIndex; this.doneSignal = doneSignal; } @Override public void run() { try { startSignal.await(); beginIndex = (beginIndex - 1) * 10 + 1; for (int i = beginIndex; i < beginIndex + 10; i++) { System.out.println(i); } } catch (InterruptedException e) { e.printStackTrace(); } finally { doneSignal.countDown(); } } } }