Latch的字面意思:弹簧锁
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yM0YGO0kjNhNTM0EzN5MTY3MDZ0gzMiNTZ0MjN3YzY08CX5d2bs92Yl1iclB3bsVmdlR2LcNWaw9CXt92Yu4GZjlGbh5yYjV3Lc9CX6MHc0RHaiojIsJye.png)
CountDownLatch是java.util.concurrent包里的一个同步工具类。
CountDownLatch的构造函数,接收一个类型为整型的参数,代表CountDownLatch所在的线程,在执行await方法后能够返回,所需要在其他线程内调用其countDown方法的次数。
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();