CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
主要方法
public CountDownLatch(int count);
public void countDown();
public void await() throws InterruptedException
构造方法参数指定了计数的次数
countDown方法,当前线程调用此方法,则计数减一
awaint方法,调用此方法会一直阻塞当前线程,直到计时器的值为0
package multiThread;import java.util.concurrent.CountDownLatch;public class Demon3 { public static void main(String[] args) { CountDownLatch countDownLatch = new CountDownLatch(3); new MyThread(countDownLatch, "thread1").start(); new MyThread(countDownLatch, "thread2").start(); new MyThread(countDownLatch, "thread3").start(); try { //等待所有进程执行完 countDownLatch.await(); System.out.println("All thread stopped"); } catch (InterruptedException e) { e.printStackTrace(); } }}class MyThread extends Thread { private CountDownLatch countDownLatch; private String threadName; public MyThread(CountDownLatch countDownLatch, String threadName) { this.countDownLatch = countDownLatch; this.threadName = threadName; } @Override public void run() { System.out.println(threadName + "RUN!!"); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(threadName + "Stopped!!"); countDownLatch.countDown(); //执行完减1 } }