某些狀況下,須要等全部線程的工做所有完成了才繼續。這時候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。線程