等待其餘線程執行完後,在執行某個線程。相似以前的join,可是比join更強大。join能夠多個線程插隊到A線程,A線程等多個線程結束後才執行(相似後面的CyclicBarrier),而CountDownLatch能夠等待多個線程執行完才執行,靈活性比join更大。segmentfault
public class CountDownLatchDemo { static CountDownLatch countDownLatch = new CountDownLatch(2); static class Thread1 implements Runnable { @Override public void run() { countDownLatch.countDown(); System.out.println(Thread.currentThread().getName() + ":" + 1); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + 2); countDownLatch.countDown(); } } public static void main(String[] args) { Thread thread =new Thread(new Thread1(),"thread"); thread.start(); try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + 3); } }
執行結果以下:
雖然線程thread休眠了2秒,可是main依然等到線程thread輸出2後,才輸出3。ide