线程工具类

CyclicBarrier官方文档

一、原理

CyclicBarrier是另外一种多线程并发控制实用工具。它和CountDownLatch非常类似,它也可以实现线程的计数等待,但它的功能比CountDownLatch更加复杂且强大。

CyclicBarrier可以理解为循环栅栏。栅栏就是一种障碍物,比如私人住宅围上一圈栅栏可以阻止闲杂人进入。它是用来阻止线程继续执行,要求线程在栅栏处等待。前面Cyclic意为循环,也就是说这个计数器可以反复使用。

二、API

 

三、Demo

四、CyclicBarrier与CountDownLatch的区别

这是CountDownLatch的官方说明

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

这是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.

CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue. 

CountDownLatch强调的是wait until(等直到),一个(多个)线程必须等待直到其它线程都完成才会执行。

也就是说我们可以对一系列复杂的操作进行切分,在不同的线程中完成,然后等待所有这些操作完成后,再使用另外一个(或多个)等候多时的线程来完成后续的操作。比如多线程下载就是一个典型例子,多个线程分别下载一个文件的一部分,等所有下载完成,合并线程开始合并。

CyclicBarrier强调的是wait for each other(相互等待),一组线程相互等待对方完成 。

原文地址:https://www.cnblogs.com/rouqinglangzi/p/7058974.html