概述
设置一个初始值count,通过count是否为0对线程的阻塞和唤醒做控制。阻塞当前线程方法CountDownLatch .await(),count值减一方法CountDownLatch.countDown()
步骤:
- 设置CountDownLatch countDownLatch=new CountDownLatch(2);的初始值count=2
- count!=0的时候,使用 countDownLatch.await();阻塞当前线程
- 让其他线程调用countDown()方法将值count值变为0
- 当count=0的时候,之前调用await()方法阻塞的线程被唤醒
案例
阻塞主线程,让t1和t2线程执行完毕后再执行主线程
public static void main(String[] args) throws InterruptedException {
//定义count的值
CountDownLatch countDownLatch=new CountDownLatch(2);
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//count值-1
countDownLatch.countDown();
}
System.out.println(Thread.currentThread().getName()+"结束");
},"t1").start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//count值-1
countDownLatch.countDown();
}
System.out.println(Thread.currentThread().getName()+"结束");
},"t2").start();
//count值不为0的时候,调用这个方法阻塞当前线程,这里是主线程
// 其他线程把count值变为0之后,调用await的线程唤醒
countDownLatch.await();
System.out.println("main 线程结束");
}
结果