一个线程(或者多个),等待另外N个线程完成某个事情之后才能执行。是并发包中提供的一个可用于控制多个线程同时开始某个动作的类,其采用的方法为减少计数的方式,当计数减至零时位于latch.Await()后的代码才会被执行,CountDownLatch是减计数方式,计数==0时释放所有等待的线程;
1. 假设两个线程必须先执行,线程三必须等两个线程结束之后再继续
public class MainCountDownLatch {
// QueryAdListTask * 2
private CountDownLatch countDownLatch = new CountDownLatch(2);
//内部类,在装载该内部类时才会去创建单例对象
private static class SingletonHolder{
public static MainCountDownLatch instance = new MainCountDownLatch();
}
private MainCountDownLatch(){}
public static MainCountDownLatch getInstance(){
return SingletonHolder.instance;
}
public CountDownLatch getCountDownLatch(){
return countDownLatch;
}
/**
* 计时器使用结束后重置
*/
public void updateCountDownLatch(){
countDownLatch = new CountDownLatch(2);
}
}
2. 两个接口调用结束,调用countDown使得计数-1
MainCountDownLatch.getInstance().getCountDownLatch().countDown();
3. 需要被暂时阻塞的线程三
MainCountDownLatch.getInstance().getCountDownLatch().await();
doSomething();
网友评论