等待其余线程执行完后,在执行某个线程。相似以前的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