![2b40dcd43f029ea6ce093b9c86f4547b.png](https://i-blog.csdnimg.cn/blog_migrate/10dc191cb34067eb80947b72646d3008.jpeg)
Latch的字面意思:弹簧锁
![03f22214029b3da0c4402a8d81276154.png](https://i-blog.csdnimg.cn/blog_migrate/dc46b9a820fd4bf55838223cbb6c8969.jpeg)
CountDownLatch是java.util.concurrent包里的一个同步工具类。
CountDownLatch的构造函数,接收一个类型为整型的参数,代表CountDownLatch所在的线程,在执行await方法后能够返回,所需要在其他线程内调用其countDown方法的次数。
![c533b7147b54820e1ec4f6d2b7005f1c.png](https://i-blog.csdnimg.cn/blog_migrate/42d3f51523df4baa6e330510655a6936.jpeg)
测试代码和打印输出:
![3e154a6fde19b94425800f43682b7f4e.png](https://i-blog.csdnimg.cn/blog_migrate/216d4f0879f4918df63521b5c7308113.jpeg)
timer.schedule新启动了一个线程,在新线程里调用countDown,而主线程执行await进入阻塞状态,待新线程调用一次countDown之后,主线程立即从await方法的阻塞状态中返回。
package jerry;
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
CountDownLatch called = new CountDownLatch(1)
println "main thread id: " + Thread.currentThread().getId();
Timer timer = new Timer()
timer.schedule(new TimerTask() {
void run() {
println "call countDown in another thread: " + Thread.currentThread().getId();
called.countDown()
}
}, 220)
println "before calling called.await in main thread: " + Thread.currentThread().getId();
called.await(10, TimeUnit.SECONDS)
println "after calling called.await in main thread: " + Thread.currentThread().getId();
要获取更多Jerry的原创文章,请关注公众号"汪子熙":
![7924123dd21a5ce5910453648a17137e.png](https://i-blog.csdnimg.cn/blog_migrate/13408450c5419b8bacc727f73920b22d.jpeg)