CountDownLatch
计数器锁
同步辅助类,允许一个或多个线程等待,直到一系列操作在其它线程中执行成功。线程调用 await 方法进行 block, 线程调用 countDown 方法减少计数器,直到 state = 0,所有wait的线程都醒来了。这个类实现的计数器是 one-shot phenomenon 的,计数器不能够被重置。
可重置的CyclicBarrier: If you need a version that resets the count, consider using a CyclicBarrier.
当 count == 1, 时,可以将 CountDownLatch 认为是一个开关.
当 count == N,时,A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.
*和其它Lock不同,lock 和 unlock 需要成对调用, await 和 countDown 这两个方法不需要线程同时调用,
Memory consistency effects: Until the count reaches zero, actions in a thread prior to calling countDown() happen-before actions following a successful return from a corresponding await() in another thread.
实现非常简洁
1 |
|
lock
1 | public void await() throws InterruptedException { |
release
1 | public void countDown() { |