某些状况下,须要等全部线程的工做所有完成了才继续。这时候CountDownLatch就派上了用场。java
public static void main(String[] args) throws InterruptedException { final CountDownLatch countDownLatch = new CountDownLatch(2); new Thread(new Runnable() { public void run() { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getId() + " -- " + i); } countDownLatch.countDown(); } }).start(); new Thread(new Runnable() { public void run() { try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getId() + " -- " + i); } countDownLatch.countDown(); } }).start(); countDownLatch.await(); System.out.println("end...."); }
在上面的demo中,必需要在两个线程都执行完成以后才会出现end。线程