CountDownLatch与CyclicBarrier的对比

CountDownLatch的官方介绍:

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

大意为:这是一种同步辅助程序,它允许一个或者多个线程进行等待,直到在其他线程中执行的一组操作执行完毕。

A CountDownLatch is initialized with a given count.The await methods block until the current count reaches zero due to invocations of the countDown method, after which all waiting threads are released and any subsequent invocations of await return immediately.  This is a one-shot phenomenon the count cannot be reset.  If you need a version that resets the count, consider using a CyclicBarrier.

大意为:使用给定的参数count进行初始化CountDownLatch对象。由于调用了countDown方法,await方法会一直阻塞,直到当前计数器count达到零,然后所有等待的线程都会被释放,并且await的后续任何调用都会立即返回。这是个一次性的机制,计数器count不能被重置。如果你想要重置计数器,那么请考虑使用CyclicBarrier。

CyclicBarrier的官方介绍:

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.  CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

大意为:这是一种同步辅助程序,它允许一组线程相互等待,知道所有线程都执行到一个相同的"屏障点"。CyclicBarriers在程序中涉及到固定大小的线程组时非常有用,这些线程组有时候必须相互等待。这个屏障被称为循环屏障,因为它可以在等待的线程被释放后重新使用。

猜你喜欢

转载自www.cnblogs.com/damour-damocles/p/12013313.html