CountDownLatch是java.util.concurrent包下的一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
主要方法:
public CountDownLatch(int count); //构造方法参数, 指定了计数的次数
public void countDown(); //调用此方法,则计数减一
public void await(); //调用此方法会一直阻塞当前线程,直到计时器的值为0
代码:
import java.util.concurrent.CountDownLatch; public class CountDownLatchTest { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(3); new Worker(1, latch).run(); new Worker(2, latch).run(); new Worker(3, latch).run(); latch.await(); System.out.println("work down..."); } } class Worker extends Thread { private int i; private CountDownLatch latch; public Worker(int i, CountDownLatch latch) { this.i = i; this.latch = latch; } @Override public void run() { if(i == 3) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } latch.countDown(); System.out.println("worker " + i + "done..."); } }